【问题标题】:Using Vue.js in Laravel 5.3在 Laravel 5.3 中使用 Vue.js
【发布时间】:2019-06-14 22:31:01
【问题描述】:

在 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 来使用文档中描述的组件,但是,我的问题是 如果我想创建一个 Vue.js。我刚才提到的 Vue.js 实例,即我严格为给定页面(不是组件)创建 Vue.js 实例我该怎么做?

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

我不应该这样做吗,我应该为所有东西创建组件吗?

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

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

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

【问题讨论】:

  • 值得一提的是,php artisan make:auth 搭建了使用捆绑的“app.js”和“app.scss”的布局和视图...

标签: javascript laravel vue.js laravel-5.3


【解决方案1】:

我会离开 Laravel 的方式,使用 Webpack。这使您能够添加一些好的 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 组件)可用于包含它的任何页面脚本。

欢迎页面脚本
现在让我们创建一个表示欢迎页面的脚本:

资源/资产/js/pages/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'
    }
})

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

资源/资产/js/pages/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'
    }
})

问候组件
resources/assets/js/components/Greeting.vue

<template>
    <div class="greeting">
       {{ message }}
    </div>
</template>

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

欢迎刀片视图
让我们更新 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 将 Webpack 配置选项与其自己的配置选项合并的能力,将它们整合到您的 gulp 文件中(阅读更多关于 here 的信息):

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 都已发布。

想法
当涉及到“网络应用程序”时,我目前正在走 SPA 路线,并且只使用 Laravel 作为后端 API(或任何其他语言/框架)。我见过一些在 Laravel 中构建 Vue SPA 的例子,但我真的认为它应该是一个完全独立的 repo/项目,独立于后端。 SPA 中不涉及 Laravel/PHP 模板视图,因此单独构建 SPA。顺便说一句,SPA 将具有“页面”组件(通常由 VueRouter 调用,当然会由更多嵌套组件组成……请参阅下面的示例项目链接)。

但是,对于“网站”,我认为 Laravel 仍然是提供刀片视图的不错选择,无需为此进行 SPA。您可以执行我在此答案中描述的操作。此外,您可以将您的网站连接到您的网络应用程序。在您的网站上,您将有一个“登录”链接,该链接会将用户从网站带到 webapp SPA 进行登录。您的网站仍然对 SEO 友好(尽管有充分证据表明 Google 也在 SPA javascript 网站上看到了内容)。

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

编辑:

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

【讨论】:

  • @haakym 请将其标记为正确答案。在不知疲倦地寻找关于如何在 5.3 中处理这个问题的正确解释之后,这真的是我见过的唯一真正的解释。
  • @prograhammer 也许你可以帮助我。看看这个:stackoverflow.com/questions/49664451/…
【解决方案2】:

如果你想使用 gulpvuejs 合并到 app.js 中,那么你可以使用 elixir 来实现:

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

npm install laravel-elixir-browserify-official

然后将以下内容放入package.json

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

您的 resources/assets/js/app.js 文件将只需要:

  require('./bootstrap');

bootstrap.js 文件应位于“resources/assets/js”文件夹中。我不记得它是否在我的应用程序中安装了护照,所以如果你没有它,那么 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>

现在只需运行 gulp

如果您不使用 elixir,那么您应该可以使用 中的 browserifywebpack 包做类似的事情npm.

编辑

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

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

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

【讨论】:

  • 嗨@craig_h 感谢您的回复,我已经更新了我的问题,让我的问题更加清晰。
  • @craig-h 感谢您的编辑,所以如果我对您的理解正确,您是说当我需要组件时使用 app.js,如果我需要单个页面的视图模型,我应该将&lt;script src="../js/vue.js"&gt;&lt;/script&gt; 放到页面中并像以前那样继续,对吗?
  • 如果您按照他的概述使用 browserify,则不需要 script 标签。 Vue 将被编译成 app.js,因此可以像往常一样使用。
  • @haakym 重要的部分是确保正确需要 Vue,因为它在提供的示例 bootstrap.js 文件中。如果它不起作用,请仔细检查编译后的 app.js 文件并确保 Vue 已正确编译。如果不是,请继续尝试。如果它在那里但仍然无法正常工作,那就更难弄清楚了。
  • @craig_h 也许你可以帮助我。看看这个:stackoverflow.com/questions/49664451/…
【解决方案3】:

如果您使用的是 Laravel 5.5 及更高版本,如果您想利用 Blade 的强大功能但仍享受 VueJS 的响应式,这里是最佳解决方案

https://stackoverflow.com/a/54349029/417899

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2017-05-17
    • 2017-03-19
    • 2017-01-25
    • 1970-01-01
    • 2017-04-21
    • 2017-03-27
    • 2017-04-28
    相关资源
    最近更新 更多