在Laravel 5.3中使用Vue.js

Using Vue.js in Laravel 5.3

本文关键字:Vue js Laravel      更新时间:2023-09-26

在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库或者我可以使用生成的app.js?

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

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

组件是Vue.js最强大的特性之一。它们帮助你扩展基本的HTML元素来封装可重用代码

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

我会让Laravel保持原样,与Webpack一起使用。这使您能够添加一些好的Webpack配置。加上gulp watch现在在Homestead流浪虚拟机中工作,因为它将使用Webpack来监视文件更改。还有async组件。

现在回到你关于每页单独的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/页面/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
现在让我们创建另一个代表Blog Page的脚本:

资源/资产/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'
    }
})
<<p> 问候组件/strong>
资源/资产/js/组件/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>

对于blog视图也是如此。


现在,使用Elixir将Webpack配置选项与自己的配置选项合并的能力,将所有这些整合到你的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同时发布。


当涉及到"web应用程序"时,我目前正在走SPA路线,只是使用Laravel作为后端API(或任何其他语言/框架)。我见过一些Vue SPA在Laravel中构建的例子,但我真的认为它应该是一个完全独立的repo/项目,独立于后端。SPA中没有涉及到Laravel/PHP模板视图,所以要单独构建SPA。顺便说一句,SPA将具有"页面"组件(通常由VueRouter调用,当然将由更多嵌套组件组成)。

然而,对于"网站",我认为Laravel仍然是提供刀片视图的好选择,不需要去SPA。你可以做我在这个答案中描述的。此外,您可以将您的网站连接到您的web应用程序。在您的网站上,您将有一个"登录"链接,将用户从网站到webapp SPA登录。你的网站仍然是SEO友好的(尽管有很好的证据表明谷歌在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

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

首先,你需要输入laravel-elixir-browserify-official from npm:

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,那么你应该可以使用npm中的browserifywebpack包来做类似的事情。

编辑

要回答你更新的问题,你当然可以使用vue.js一个页面。我个人使用knockout(我使用vue,因为laravel passport使用它),但在架构上它们是相同的——它们是MVVM库。

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

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

如果你使用的是Laravel 5.5及以上版本,如果你想利用Blade的强大功能,但仍然享受VueJS的响应性,这里是最好的解决方案

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