首頁  >  文章  >  php框架  >  vuejs怎麼跟thinkphp結合

vuejs怎麼跟thinkphp結合

(*-*)浩
(*-*)浩原創
2019-07-15 09:55:2320915瀏覽

vue在服務端部署時,我們都知道透過npm run build 指令打包好的dist文件,透過http指定是可以直接瀏覽的,Thinkphp透過網域指向index.php檔案才可以瀏覽。要使前端正常調用後端資料。

vuejs怎麼跟thinkphp結合

有兩種方法:

1、前端跨域呼叫後端數據。

2、前端打包檔案部署在後端的伺服器資料夾下(同域)。

web伺服器:apache

如:跨網域

#在伺服器設定站:

在路径/home/www/  下创建test项目文件夹,用来放项目文件。
找到httpd-vhosts.conf文件配置站点
前端站点:
<VirtualHost *:80>
    ServerName test.test.com
    DocumentRoot "/home/www/test/dist"  
    DirectoryIndex index.html
</VirtualHost>
后端站点:
<VirtualHost *:80>
    ServerName test.testphp.com
    DocumentRoot "/home/www/test/php"  
    DirectoryIndex index.php
</VirtualHost>

將前端打包好的dist檔案放在/home/www/test/ 資料夾下,執行http://test.test.com可瀏覽,當路徑改變時,刷新會出現404錯誤。此時在dist檔案下建立一個.htaccess文件,當路徑不存在時,路徑指向http://test.test.com/index.html能解決此問題。

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

在/home/www/test資料夾下建立專案根目錄php資料夾,將thinkphp檔案放在php下。 TP5的入口檔案在public檔案下,在這將public下的入口檔案index.php挪到php資料夾下(個人習慣將入口檔案放在專案根目錄), 後端綁定Index模組。

前端調用後端接口,存在跨域,跨域解決方法有好幾種,在這我將在後端php做配置,解決跨域問題,在公用控制器設置跨域配置:

class Common extends Controller
{
    public $param;
    // 设置跨域访问
    public function _initialize()
    {
        parent::_initialize();
        isset($_SERVER['HTTP_ORIGIN']) ? header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']) : '';
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, authKey, sessionId");
        $param =  Request::instance()->param();
        $this->param = $param;
    }
}

前端呼叫登入介面: this.axios.post('http://test.testphp.com/index.php/base/login', {user: '', password: ''}) 。

(可在webpack.base.conf.js檔案下可定義介面:http://test.testphp.com/index.php/)

同域

後端配置同上,公共配置器中的header配置註解。將前端的dist檔案下的所有檔案(包含.htaccess),放在php資料夾下。將後端index控制器的index方法的路徑重定向php下的index.html檔:

namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index() {
        $this->redirect('/index.html');
}

前端呼叫登入介面:this.axios.post('/index.php/base/login', {user: '', password: ''})

更多Thinkphp相關技術文章,請造訪Thinkphp教學欄位學習!

以上是vuejs怎麼跟thinkphp結合的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn