在 Laravel 5.3 中使用 Vue.js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39708680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Vue.js in Laravel 5.3
提问by haakym
In Laravel projects prior to 5.3 I've utilised Vue.js using the script tag like this:
在 5.3 之前的 Laravel 项目中,我使用 Vue.js 使用脚本标记,如下所示:
<script type="text/javascript" src="../js/vue.js"></script>
I would then create a Vue instance specific for that page like this:
然后我将创建一个特定于该页面的 Vue 实例,如下所示:
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
});
</script>
and then bind it to the relevant div#id in my HTML.
然后将其绑定到我的 HTML 中的相关 div#id。
Now, in Laravel 5.3 Vue.js comes bundled and I am fully aware that I can use components as described in the docs by using gulp/elixir, however, my question is 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?
现在,在 Laravel 5.3 中 Vue.js 是捆绑的,我完全知道我可以通过使用 gulp/elixir 来使用文档中描述的组件,但是,我的问题是我是否想创建一个 Vue.js 实例,就像我刚才提到的,即我严格为给定页面(不是组件)创建 Vue.js 实例的地方我该怎么做?
Do I set it up like I used to by importing the vue.js library in a script tag or can I use generated app.js?
我是像以前一样通过在脚本标签中导入 vue.js 库来设置它,还是可以使用生成的 app.js?
Am I not supposed to do it this way, should I be creating components for everything?
我不应该这样做吗,我应该为所有东西创建组件吗?
For me, it doesn't make sense to make a component for something I am only using once - I thought the purpose of components was that they are reusable - you can use it in more than one place. As mentioned in the Vue.js docs:
对我来说,为我只使用一次的东西制作一个组件是没有意义的——我认为组件的目的是它们是可重用的——你可以在多个地方使用它。正如 Vue.js 文档中提到的:
Components are one of the most powerful features of Vue.js. They help you extend basic HTML elements to encapsulate reusable code.
组件是 Vue.js 最强大的特性之一。它们帮助您扩展基本的 HTML 元素以封装可重用的代码。
Any advice would be appreciated, thanks!
任何建议将不胜感激,谢谢!
回答by prograhammer
I'd leave Laravel the way it comes, with Webpack. This gives you the ability to add some good Webpack configuration. Plus gulp watch
works inside the Homestead vagrant VM now since it will be using Webpack to watch the file changes. And also check out async components.
我会用 Webpack 离开 Laravel。这使您能够添加一些好的 Webpack 配置。Plusgulp watch
现在在 Homestead vagrant VM 中工作,因为它将使用 Webpack 来观察文件更改。并检查异步组件。
Now on to your question regarding separate Vue instances per page...let's start with app.js...
现在讨论关于每页单独的 Vue 实例的问题……让我们从 app.js 开始……
App.js
When you first install Laravel 5.3, you'll find an app.js
entry point. Let's comment out the main Vue instance:
App.js
当你第一次安装 Laravel 5.3 时,你会发现一个app.js
入口点。让我们注释掉主要的 Vue 实例:
resources/assets/js/app.js
资源/资产/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'
// });
The app.js
file still remains a place to for global stuff, so components added here are available (such as the example
component seen above) to any page script that includes it.
该app.js
文件仍然是用于放置全局内容的地方,因此此处添加的example
组件(例如上面看到的组件)可用于包含它的任何页面脚本。
Welcome Page Script
Now let's create a script that represents a Welcome Page:
欢迎页面脚本
现在让我们创建一个表示欢迎页面的脚本:
resources/assets/js/pages/welcome.js
资源/资产/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'
}
})
Blog Page Script
Now let's create another script that represents a Blog Page:
博客页面脚本
现在让我们创建另一个代表博客页面的脚本:
resources/assets/js/pages/blog.js
资源/资产/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'
}
})
Greeting Component
resources/assets/js/components/Greeting.vue
问候组件
资源/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>
Welcome Blade View
Let's update the welcome blade view that ships with Laravel:
欢迎刀片视图
让我们更新 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>
The idea would be the same for the blog view.
博客视图的想法是相同的。
Elixir
Now bring it all together in your gulp file using Elixir's ability to merge Webpack config options with its own (read more about that here):
Elixir
现在使用 Elixir 将 Webpack 配置选项与自己的配置选项合并的能力,将它们整合到你的 gulp 文件中(在此处阅读更多相关信息):
gulpfile.js
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);
});
Run gulp
or gulp watch
and you'll see both welcome.js
and blog.js
published.
运行gulp
或gulp watch
,您将看到两者welcome.js
并blog.js
已发布。
Thoughts
I'm currently going the SPA route when it comes to "web apps" and just using Laravel as the backend API (or any other language/framework). I've seen some examples where Vue SPA is built in Laravel, but I really think it should be a completely seperate repo/project, independent of the backend. There's no Laravel/PHP templating views involved in an SPA, so build out the SPA separately. BTW, the SPA would have "page" components (which are usually called by VueRouter and of course would be made up of more nested components...see my example project link below).
想法
当涉及到“网络应用程序”时,我目前正在走 SPA 路线,并且只使用 Laravel 作为后端 API(或任何其他语言/框架)。我见过一些在 Laravel 中构建 Vue SPA 的例子,但我真的认为它应该是一个完全独立的 repo/项目,独立于后端。SPA 中不涉及 Laravel/PHP 模板视图,因此单独构建 SPA。顺便说一句,SPA 将具有“页面”组件(通常由 VueRouter 调用,当然由更多嵌套组件组成...请参阅下面的示例项目链接)。
However, for the "web site" I think Laravel is still a good choice for serving blade views and no need to go SPA for that. You can do what I've described in this answer. Also, you can connect your website to your webapp. On your website, you would have a "login" link that will take a user from the website to the webapp SPA to login. Your website remains SEO friendly (although there is good proof that Google is seeing content on SPA javascript sites as well).
但是,对于“网站”,我认为 Laravel 仍然是提供刀片视图的不错选择,无需为此而使用 SPA。你可以做我在这个答案中描述的。此外,您可以将您的网站连接到您的 web 应用程序。在您的网站上,您会有一个“登录”链接,该链接会将用户从网站带到 webapp SPA 进行登录。您的网站仍然对 SEO 友好(尽管有充分的证据表明 Google 也在 SPA javascript 网站上看到内容)。
For a look at an SPA approach, I've put up an example in Vue 2.0 here: https://github.com/prograhammer/example-vue-project(it works great, but still in progress).
为了了解 SPA 方法,我在 Vue 2.0 中提供了一个示例:https: //github.com/prograhammer/example-vue-project(效果很好,但仍在进行中)。
Edit:
编辑:
You may want to also checkout the Commons Chunk Plugin. This way browsers can cache some shared module dependencies separately. Webpack automatically can pull out shared imported dependencies and put them in a separate file. So that you have a both a common.js
(shared stuff) and a welcome.js
on a page. Then on another page you would again have common.js
and blog.js
and the browser can reuse the cached common.js
.
您可能还想查看Commons Chunk Plugin。这样浏览器可以单独缓存一些共享的模块依赖项。Webpack 可以自动提取共享的导入依赖项并将它们放在单独的文件中。这样您就可以在页面上同时拥有 a common.js
(共享内容)和 a welcome.js
。然后在另一个页面上,您将再次拥有common.js
并且blog.js
浏览器可以重用缓存的common.js
.
回答by craig_h
If you want to incorporate vuejsinto app.jsusing gulpthen you can do it with elixir:
如果要合并vuejs到app.js使用一饮而尽,然后你可以用灵药做到这一点:
Firstly, you need laravel-elixir-browserify-officialfrom npm:
首先,你需要来自 npm 的laravel-elixir-browserify-official:
npm install laravel-elixir-browserify-official
npm install laravel-elixir-browserify-official
Then place the following in package.json:
然后将以下内容放入package.json:
"browserify": {
"transform": [
"vueify",
"babelify"
]
}
Your resources/assets/js/app.jsfile would then just need:
你的resources/assets/js/app.js文件只需要:
require('./bootstrap');
The bootstrap.jsfile should be in the "resources/assets/js" folder. I can't remember if this got installed with passport in my application, so if you don't have it then laravel provided the following code for "bootstrap.js":
该bootstrap.js文件应在“资源/资产/ JS”文件夹中。我不记得它是否在我的应用程序中安装了 Passport,所以如果你没有它,那么 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'
// });
Now in gulpfile.jsyou can use:
现在在gulpfile.js 中你可以使用:
elixir(function(mix) {
mix.browserify('app.js');
});
And in your HTML you would have:
在您的 HTML 中,您将拥有:
...
<div id="app">
@{{message}}
</div>
...
<script type="text/javascript">
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
}
});
</script>
Now just run gulp
现在只需运行gulp
If you are not using elixirthen you should be able to do a similar thing with the browserifyor webpackpackages from npm.
如果你不使用灵药,那么你应该可以做类似的事情与browserify或的WebPack从包NPM。
Edit
编辑
To answer your updated question, you can of course use vue.js for a single page. I personally use knockout for this stuff (I'm using vue because laravel passport uses it), but architecturally they are the same - they are MVVM libraries.
要回答您更新的问题,您当然可以将 vue.js 用于单个页面。我个人对这些东西使用淘汰赛(我使用 vue 是因为 laravel 护照使用它),但在架构上它们是相同的 - 它们是 MVVM 库。
The point in MVVM is to bind your view to an underlying data model, so when one updates the other is automatically updated (i.e. updates in the dom automatically update the model and vice verser). Vue components are a simple way to reuse blocks of code, which is really good for creating widgets or complex components, but if you are simply looking to render data from a view model on to your page, then you would not usually need to create a component for that.
MVVM 中的重点是将您的视图绑定到底层数据模型,因此当一个更新时另一个会自动更新(即 dom 中的更新自动更新模型,反之亦然)。Vue 组件是一种重用代码块的简单方法,这对于创建小部件或复杂组件非常有用,但是如果您只是想将视图模型中的数据呈现到您的页面上,那么您通常不需要创建一个组件。
As for generating app.js, this entirely depends on your project. You cannot bind more than one view model to a view, so if you plan on using multiple view models in your project you would need to find a way to include the specific view model for your page. To achieve that I would probably remove the view model from app.js and keep the bootstrap and registered components there, then create separate view models that would need to be included on each page.
至于生成 app.js,这完全取决于你的项目。您不能将多个视图模型绑定到一个视图,因此如果您计划在项目中使用多个视图模型,您需要找到一种方法来为您的页面包含特定的视图模型。为了实现这一点,我可能会从 app.js 中删除视图模型并将引导程序和注册组件保留在那里,然后创建需要包含在每个页面中的单独视图模型。
回答by cyberfly
If you are on Laravel 5.5 and beyond, here is the best solution if you want to utilize the power of Blade but still enjoy reactive of VueJS
如果您使用的是 Laravel 5.5 及更高版本,如果您想利用 Blade 的强大功能但仍然享受 VueJS 的响应式,这里是最佳解决方案