美文网首页laravel
入坑vue laravel,配置vue-router和axios

入坑vue laravel,配置vue-router和axios

作者: Noname_ec22 | 来源:发表于2019-02-18 10:24 被阅读577次

    laravel和vue是老搭档了但是想搭建好这个平台对刚刚接触这些东西的(我)还是非常复杂的

    首先感谢一篇CSDN的文章让我觉得CSDN上还不全是复制的东西
    Laravel5.5 + Vue2 + Element 环境搭建-作者-潜心做事CG

    搭建过程

    1.首先安装composer

    composer是一个非常厉害的东西

    我是mac环境 brew install composer

    或者使用composer.phar的局部操作也行,
    以下是下载composer.phar的命令转自getcomposer

    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php -r "if (hash_file('sha384', 'composer-setup.php') === '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
    php composer-setup.php
    php -r "unlink('composer-setup.php');"
    
    

    2.创建Laravel项目

    laravel是一个很漂亮又具有内涵的php框架

    我给新项目起名叫做Larvuent了来源于一篇CSDN文章

    composer create-project --prefer-dist laravel/laravel Larvuent

    cd Larvuent

    这就算创建完成了吧

    3.安装依赖库

    安装之前要先安装好node和npm的环境

    $node -v
    v10.15.1
    $npm -v
    6.7.0
    

    进入项目之后
    npm install
    速度慢的尽量使用代理,cnpm还是容易翻车,或者多等会儿

    bash怎么使用代理之后再说

    安装完成之后我们先看一下有个public目录,这就是服务目录我们先使用

    php -S localhost:8080 -t public/

    然后去服务器看看服务启动没有


    Screen Shot 2019-02-17 at 11.26.16 PM.png

    服务已经启动了

    4.修改路由(我的习惯而已)

    如果不知道路由是什么建议先了解一下php的基础

    修改 routes/web.php 文件为

    Route::get('/', function () {
        return view('index');
    });
    

    5.新建vue测试连通性

    resource/js/components下其实已经有了一个ExampleComponent.vue

    $cat ExampleComponent.vue
    <template>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card card-default">
                        <div class="card-header">Example Component</div>
    
                        <div class="card-body">
                            I'm an example component.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
    
    <script>
        export default {
            mounted() {
                console.log('Component mounted.')
            }
        }
    </script>
    

    6.修改 app.js 文件,渲染组件

    修改resources/assets/js/app.js文件

    require('./bootstrap');
    
    window.Vue = require('vue');
    
    import ExampleComponent from './components/ExampleComponent.vue'; // 引入Hello 组件
    
    const app = new Vue({
        el: '#app',
        render: h => h(ExampleComponent)
    });
    

    说明:app.js 是构建 Vue 项目的主文件,最后所有的组件都会被引入到这个文件,在引入所有组件之前,bootstrap.js 文件做了一些初始化的操作。同时,因为有了 window.Vue = require(‘vue’) 这句话,就不再需要使用 import Vue from ‘vue’ 重复导入 Vue 了。

    7.新建 Laravel 视图文件,和 Vue 交互

    在 resources/views 目录下新建 index.blade.php 文件

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Larvuent</title>
    </head>
    <body>
        <div id="app"></div>
    
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>
    

    说明:你可能在其他教程中看到有的在使用 assets 函数,这两个函数的主要区别就是 assets 函数会直接使用所填路径去 public 文件夹下找文件,而 mix 函数会自动加载带 hash 值的前端资源。这是和 Laravel 前端资源的缓存刷新相关的,如果现在还不明白,不要紧,你记得使用 mix 函数就好了,然后继续往后看。

    8.编译前端组件,运行

    执行以下命令,编译前端资源

    npm run dev

    然后我们再次来到项目根目录

    php -S localhost:8080 -t public/

    其实上面这个可以不关,我们再开一个窗口来完成其余内容就行了啦

    Screen Shot 2019-02-17 at 11.49.28 PM.png

    9.引入ElementUI

    在项目中执行

    npm i element-ui -S

    过程会慢点稍等

    resources/assets/js/app.js中引入组件

    //添加如下几行来引入
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);
    

    10.修改 Hello.vue 文件,使用 Element 组件

    修改其中template为

    <template>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card card-default">
                        <div class="card-header">Example Component</div>
    
                        <div class="card-body">
                            I'm an example component.
                        </div>
                         <el-button @click="visible = !visible">按钮</el-button>
                        <el-col v-show="visible">欢迎使用 Element</el-col>
                    </div>
                </div>
            </div>
        </div>
    </template>
    

    同时下方的数据也要使用data(){return{}}的方式给出

    <script>
        export default {
            data(){
                return {
                    visible:false
                }
            },
            mounted() {
                console.log('Component mounted.')
            }
        }
    </script>
    

    11.再次编译运行

    除了php -S跑在后台之外
    我们可以使用npm run watch来让vue自己监视前端改变然后自动编译资源

    再次访问效果如下

    Screen Shot 2019-02-18 at 12.01.30 AM.png

    其实整个项目已经搭建完成了


    完善

    细心的人会发现

    Screen Shot 2019-02-18 at 12.04.51 AM.png

    这里有个CSRF报错,在view.blade.php中加一行
    <meta name="csrf-token" content="{{ csrf_token() }}">加在
    <meta charset="UTF-8">旁边即可解决问题

    下方然后加好之后的文件为

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Larvuent</title>
    </head>
    <body>
        <div id="app"></div>
    
        <script src="{{ mix('js/app.js') }}"></script>
    </body>
    </html>
    

    Vue-router的引入

    这个包的引入会改变你对前端的看法,用了之后会觉得前端真的是拼起来的

    1.安装

    npm install vue-router --save-dev

    2.配置 vue-router

    在 resources/assets/js 目录下新建目录 router ,同时在 router 目录下新建 index.js 文件

    // resources/assets/js/router/index.js
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
    
    export default new VueRouter({
        saveScrollPosition: true,
        routes: [
            {
                name: 'index',
                path: '/',
                component: resolve => void(require(['../components/ExampleComponent.vue'], resolve))
            }
        ]
    });
    

    3.引入vue-router

    按照标准在resources/assets/js下新建文件App.vue

    // resources/assets/js/App.vue
    <template>
        <div>
            <h1>Hello, {{ msg }}!</h1>
            <router-view></router-view> <!--路由引入的组件将在这里被渲染-->
        </div>
    </template>
    
    <script>
    export default {
        data() {
            return {
                msg: 'Vue'
            }
        }
    }
    </script>
    
    <style>
    </style>
    

    4.修改app.js

    修改 resources/assets/js/app.js 文件为

    import router from './router/index.js';  
    
    import Vue from 'vue';
    import App from './App.vue';
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);
    
    
    const app = new Vue({
        el: '#app',
        router,
        render: h => h(App)
    });
    

    虽然app.js和index.js里重复引入了vue,但是暂未找到解决方法

    axios请求数据

    1.安装axios

    我记得直接安装axios会报错
    先执行

    npm install axios

    再执行

    npm install --save axios vue-axios

    然后再app.js里添加这几条

    import axios from 'axios'
    
    Vue.prototype.$http = axios;
    

    以下是一个post方法的实例,其中有几个点相当坑人
    1.首先你是必须在headers里添加
    CSRF保护

    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

    完全示例如下

    this.$http.post('/api/user/login', {
                        "username": this.username,
                        "password": this.password,
                        headers: {
                            // language=JQuery-CSS
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        }
                    }).then((response) => {
                        if (response.data.status
                        ) {
                            console.log('登录成功');
                        } else {
                            console.log('登录失败')
                        }
                    }).error((error) => {
                        alert('当前网络状态不好,请稍后刷新重试');
                        console.log(error);
                    });
    

    2..then(...).error(...);有两种写法
    一种是同以下8行和15行一样

    .then((response)=>{
    ...
    }).error((error)=>{
    ...
    });
    

    以上这种可以在中间使用this指代Vue来访问data中的数据,

    还有一种是坑了我好久的

    .then(function(response){
    //这里面写this好像指代的是axios组件
    }).error(function(error){
    
    });
    

    以上为第二种是不能用this访问的,要用self,真的是坑了太久

    2.写一段示范一下

    由于用外部的API有时候会有奇怪问题有关CSRF保护之类的,因此我们打开route/web.php中添加一条

    Route::get('/test',function(){
       return "success"; 
    });
    

    忘了说axios并不是vue的组件,我们安装了vue-axios是可以直接引用的

    我们可以在app.js中删除掉Vue.prototype.$http = axios;

    添加一下两条

    import VueAxios from 'vue-axios'
    
    Vue.use(VueAxios,axios)
    

    然后我们在ExampleComponent.vue中修改mounted部分

    mounted: function() {
        let url = "/test";
        this.axios.get(url).then(response => {
          this.test = response;
          console.log("加载成功");
        });
      }
    

    至于mounted是干什么的之后各位了解一下vue的生命线即可

    我们在模板中添加一行将数据渲染到此处

    {{this.test["data"]}}

    你可能还没启动服务

    (在项目的根目录)开启一个终端输入php -S localhost:8081 -t public/

    再开启一个输入npm run watch

    然后我们访问一下即可看到console打印加载成功,字样内容渲染到界面了

    Screen Shot 2019-02-18 at 9.58.00 AM.png

    还有很多新玩意儿vuex啥的还有有关mix的问题之后再说
    我把整个项目放在了GitHub链接

    vue-laravel-template

    有什么问题欢迎戳我

    相关文章

      网友评论

        本文标题:入坑vue laravel,配置vue-router和axios

        本文链接:https://www.haomeiwen.com/subject/ofgoeqtx.html