编辑2
使用`window.games,这将“注册”全局变量。
虽然,我所做的是以下,考虑MPA不是SPA:
在app.js中,我只留下以下几行:
require('./bootstrap');
window.Vue = require('vue');
在我制作的另一个名为main.js的文件中,我将其作为示例:
import Sidebar from './components/layouts/Sidebar.vue'
import Topnav from './components/layouts/Topnav.vue'
new Vue({
el: '#sidebar',
render: h => h(Sidebar)
});
new Vue({
el: '#topnav',
render: h => h(Topnav)
});
在app.blade.php的末尾,我将:
<script src="{{ asset('js/app.js') }}"></script>
<script type="text/javascript">
const user_props = {
fullName : {!! json_encode(Auth::user()->fullName) !!},
username : {!! json_encode(Auth::user()->username) !!},
}
user_props.install = function(){
Object.defineProperty(Vue.prototype, '$userProps', {
get () { return user_props }
})
}
Vue.use(user_props);
</script>
<script src="{{ asset('js/main.js') }}"></script>
这是因为我在app.js中安装了vue,但是
user_props
在我声明并安装原型后加载。。。另外,由于vue安装在app.js中,因此我可以使用
Vue.use(user_props);
加载后。。。
忘了在webpack.mix.js中添加main.js:
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.js('resources/js/main.js', 'public/js/')
编辑1
根据您的评论和文档:
https://vuejs.org/v2/cookbook/adding-instance-properties.html#The-Importance-of-Scoping-Instance-Properties
这个
$
这只是一个惯例:
... 我们使用$scope实例属性来避免这种情况。如果愿意,您甚至可以使用自己的约定,例如$\u appName或appName,以防止与插件或将来的功能发生冲突。
Vue.prototype.games = games;
然后,您可以在每个组件上访问它
this.games
正如文档所暗示的,在执行此操作时,必须小心不要覆盖它。因此,如果您在Vue组件的数据部分声明了它,我认为您应该删除这些行。。。