首页 文章

在Laravel 5.3中使用Vue.js.

提问于
浏览
21

在5.3之前的Laravel项目中,我使用脚本标记使用了Vue.js,如下所示:

<script type="text/javascript" src="../js/vue.js"></script>

然后我会创建一个特定于该页面的Vue实例,如下所示:

<script>
    new Vue({
      el: '#app',
      data: {
        message: 'Hello Vue.js!'
      }
    });
</script>

然后将其绑定到我的HTML中相关的div#id .

现在,在Laravel 5.3中捆绑了Vue.js,我完全清楚我可以使用gulp / elixir来使用文档中描述的组件,但是,我的问题是 if I want to create a Vue.js instance like I just mentioned, i.e. where I create a Vue.js instance strictly for a given page (not a component) how do I do it?

我是否像以前一样通过在脚本标记中导入vue.js库来设置它,还是可以使用生成的app.js?

我不应该这样做,我应该为一切创建组件吗?

对我来说,为我只使用一次的东西制作一个组件是没有意义的 - 我认为组件的目的是它们可以重复使用 - 你可以在不止一个地方使用它 . 如Vue.js文档中所述:

组件是Vue.js最强大的功能之一 . 它们可以帮助您扩展基本HTML元素以封装可重用代码 .

任何建议将不胜感激,谢谢!

2 回答

  • 27

    我会用Webpack离开Laravel . 这使您能够添加一些良好的Webpack配置 . 加上 gulp watch 现在在Homestead vagrant VM中工作,因为它将使用Webpack来监视文件更改 . 并查看异步组件 .

    现在回答你关于每页单独的Vue实例的问题......让我们从app.js开始......

    App.js
    首次安装Laravel 5.3时,您会找到 app.js 入口点 . 让我们注释掉主要的Vue实例:

    资源/资产/ JS / app.js

    /**
     * First we will load all of this project's JavaScript dependencies which
     * include Vue and Vue Resource. This gives a great starting point for
     * building robust, powerful web applications using Vue and Laravel.
     */
    
    require('./bootstrap');
    
    /**
     * Next, we will create a fresh Vue application instance and attach it to
     * the page. Then, you may begin adding components to this application
     * or customize the JavaScript scaffolding to fit your unique needs.
     */
    
    Vue.component('example', require('./components/Example.vue'));
    
    // Let's comment this out, each page will be its own main Vue instance.
    //
    // const app = new Vue({
    //     el: '#app'
    // });
    

    app.js 文件仍然是全局内容的地方,因此这里添加的组件可用于包含它的任何页面脚本(例如上面看到的 example 组件) .

    Welcome Page Script
    现在让我们创建一个代表欢迎页面的脚本:

    资源/资产/ JS /页/ welcome.js

    require('../app')
    import Greeting from '../components/Greeting.vue' 
    
    var app = new Vue({
        name: 'App',
        el: '#app',
        components: { Greeting },
        data: {
            test: 'This is from the welcome page component'
        }
    })
    

    Blog Page Script
    现在让我们创建另一个代表博客页面的脚本:

    资源/资产/ JS /页/ blog.js

    require('../app')
    import Greeting from '../components/Greeting.vue' 
    
    var app = new Vue({
        name: 'App',
        el: '#app',
        components: { Greeting },
        data: {
            test: 'This is from the blog page component'
        }
    })
    

    Greeting Component
    资源/资产/ JS /组件/ Greeting.vue

    <template>
        <div class="greeting">
           {{ message }}
        </div>
    </template>
    
    <script>
        export default {
            name: 'Greeting',
            data: () => {
                return {
                    message: 'This is greeting component'
                }
            }
        }
    </script>
    

    Welcome Blade View
    让我们更新Laravel附带的欢迎刀片视图:

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
    
            <title>Laravel</title>
        </head>
        <body>
            <div id="app">
                <example></example>
                @{{ pageMessage }}
                <greeting></greeting>
            </div>
    
            <script src="/js/welcome.js"></script>
        </body>
    </html>
    

    博客视图的想法是一样的 .

    Elixir
    现在使用Elixir将Webpack配置选项与其自身合并的功能(在here中了解更多内容)将所有内容整合到您的gulp文件中:

    gulpfile.js

    const elixir = require('laravel-elixir');
    
    require('laravel-elixir-vue-2');
    
    /*
     |--------------------------------------------------------------------------
     | Elixir Asset Management
     |--------------------------------------------------------------------------
     |
     | Elixir provides a clean, fluent API for defining some basic Gulp tasks
     | for your Laravel application. By default, we are compiling the Sass
     | file for our application, as well as publishing vendor resources.
     |
     */
    
    elixir(mix => {
        var config =  elixir.webpack.mergeConfig({
              entry: {
                welcome: './resources/assets/js/pages/welcome.js',
                blog: './resources/assets/js/pages/blog.js'
              },
              output: {
                filename: '[name].js' // Template based on keys in entry above
              }
           });
    
        mix.sass('app.scss')
           .webpack('app.js', null, null, null, config);
    });
    

    运行 gulpgulp watch ,您将看到 welcome.jsblog.js 已发布 .

    Thoughts
    我已经看到了Vue SPA在Laravel中构建的一些例子,但我认为它应该是一个完全独立的repo /项目,独立于后端 . SPA中没有涉及Laravel / PHP模板视图,因此请单独构建SPA . 顺便说一下,SPA会有"page"组件(通常由VueRouter调用,当然也会由更多嵌套组件组成...请参阅下面的示例项目链接) .

    但是,对于“网站”,我认为Laravel仍然是提供刀片视图的不错选择,而且无需为此提供SPA . 你可以做我在这个答案中描述的内容 . 此外,您可以将您的网站连接到您的网络应用程序 . 在您的网站上,您将拥有一个“登录”链接,该链接将用户从网站到webapp SPA进行登录 . 您的网站仍然是SEO友好的(虽然有很好的证据表明Google也在SPA javascript网站上看到内容) .

    为了了解SPA方法,我在Vue 2.0中提供了一个示例:https://github.com/prograhammer/example-vue-project(它工作得很好,但仍在进行中) .

    Edit:

    您可能还想查看Commons Chunk Plugin . 这样浏览器可以单独缓存一些共享模块依赖项 . Webpack可以自动提取共享的导入依赖项并将它们放在一个单独的文件中 . 这样你就可以在页面上同时拥有 common.js (共享内容)和 welcome.js . 然后在另一个页面上,您将再次拥有 common.jsblog.js ,并且浏览器可以重用缓存的 common.js .

  • 7

    如果你想使用gulp将vuejs合并到app.js中,那么你可以使用elixir:

    首先,你需要来自npm的laravel-elixir-browserify-official:

    npm install laravel-elixir-browserify-official

    然后将以下内容放在package.json中:

    "browserify": {
        "transform": [
          "vueify",
          "babelify"
        ]
      }
    

    您的资源/资产/ js / app.js文件只需要:

    require('./bootstrap');
    

    bootstrap.js文件应位于"resources/assets/js"文件夹中 . 我可以't remember if this got installed with passport in my application, so if you don' t然后laravel为"bootstrap.js"提供了以下代码:

    window._ = require('lodash');
    
    /**
     * We'll load jQuery and the Bootstrap jQuery plugin which provides support
     * for JavaScript based Bootstrap features such as modals and tabs. This
     * code may be modified to fit the specific needs of your application.
     */
    
    window.$ = window.jQuery = require('jquery');
    require('bootstrap-sass');
    
    /**
     * Vue is a modern JavaScript library for building interactive web interfaces
     * using reactive data binding and reusable components. Vue's API is clean
     * and simple, leaving you to focus on building your next great project.
     */
    
    window.Vue = require('vue');
    require('vue-resource');
    
    /**
     * We'll register a HTTP interceptor to attach the "CSRF" header to each of
     * the outgoing requests issued by this application. The CSRF middleware
     * included with Laravel will automatically verify the header's value.
     */
    
    Vue.http.interceptors.push((request, next) => {
        request.headers['X-CSRF-TOKEN'] = Laravel.csrfToken;
    
        next();
    });
    
    /**
     * Echo exposes an expressive API for subscribing to channels and listening
     * for events that are broadcast by Laravel. Echo and event broadcasting
     * allows your team to easily build robust real-time web applications.
     */
    
    // import Echo from "laravel-echo"
    
    // window.Echo = new Echo({
    //     broadcaster: 'pusher',
    //     key: 'your-pusher-key'
    // });
    

    现在在gulpfile.js中你可以使用:

    elixir(function(mix) {
        mix.browserify('app.js');
    });
    

    并在您的HTML:

    ...
    <div id="app">
      @{{message}}
    </div>
    ...
    
    <script type="text/javascript">
       new Vue({
         el: '#app',
         data: {
           message: 'Hello Vue.js!'
         }
      });
    </script>
    

    现在就跑了一口气

    如果您没有使用elixir,那么您应该可以使用npm中的browserify或webpack包进行类似的操作 .

    Edit

    要回答您更新的问题,您当然可以将vue.js用于单个页面 . 我个人使用淘汰赛这些东西(我使用vue因为laravel passport使用它),但在架构上它们是相同的 - 它们是MVVM库 .

    MVVM中的要点是将您的视图绑定到底层数据模型,因此当一个更新时,另一个更新会自动更新(即dom中的更新会自动更新模型和反之亦然) . Vue组件是重用代码块的简单方法,这对于创建窗口小部件或复杂组件非常有用,但如果您只是想将视图模型中的数据呈现到页面上,那么通常不需要创建组件 .

    至于生成app.js,这完全取决于您的项目 . 您不能将多个视图模型绑定到视图,因此如果您计划在项目中使用多个视图模型,则需要找到一种方法来包含页面的特定视图模型 . 为了实现这一目标,我可能会从app.js中删除视图模型并将引导程序和注册组件保留在那里,然后创建需要包含在每个页面上的单独视图模型 .

相关问题