Vus.js 2.0 Laravel 5.4 将对象传递给应用程序并跨组件全局使用它

Vus.js 2.0 Laravel 5.4 pass object to app and use it globally accross components

我想加载经过身份验证的用户并在我所有的 vue 组件中使用它(没有不必要的 ajax 请求,因为我可以直接从后端加载它)。

我的 Laravel home.blade.php 引用了一个 Vue 应用程序,我尝试将 Auth::user() 绑定到主视图:

<div id="app" :authuser="{{ Auth::user() ? : '[]' }}"></div>

我的 app.js 文件如下所示:

const app = new Vue({
  el: '#app',
  props: ['authuser'],
  data: { authuser: this.authuser }
});

但是您似乎无法将 props 传递给主要的 Vue 对象。最好的方法是什么?

注意: 除了通过道具,我愿意接受其他建议。理想情况下,我想从我所有的 vue 组件全局引用一个 authuser 对象。例如,也许通过 window.authuser

一种方法是使用 $root. As suggested here,您应该能够在 app 组件中设置并跨组件使用它。

在你的app.js中:

const app = new Vue({
  el: '#app',
  created () {
    // will fire the first time the router is loaded,
    // and won't be called again until page refresh
    // maybe load in your data dynamically?
    this.$root.authuser = this.authuser;
  }
});

然后在你的组件中:

this.$root.authuser

其他方法可以使用 central state or vuex which is more popular among the community. You can have a look at similar answer . You can commit to vuex mutation in the created/mounted block of app.js and later can access it in any components with help of getters.

在调用 app.js 之前将其添加到 blade 模板中可以达到目的:

<script>
  let authuser = {!! Auth::user() ? : '[]' !!};
</script>
<script src="{{asset('js/app.js') }}"></script>

这将允许您在任何组件中直接和全局使用 authuser,例如:

<template>
  <div class="answer" v-if="authUserAnswered">
     Edit Answer
  </div>
</template>

<script>
  export default {
    props: ['answer'],
    computed: {
      authUserAnswered() { return authuser.id == this.answer.user_id; }
    }
  }
</script>

这比每次都使用 this.$root 更干净。

您可以了解有关 Shared States here 的更多信息。

在app.js中,可以声明全局变量。

例如:

// app.js
global.user = 'hello';

// anywhere else, you can access the user var
console.log(user);

您也可以将其应用于 vue 对象本身(如果需要):

global.vm = new Vue({
    methods: {
        helloWorld(){}
    }
});

并且您将能够从其他组件访问它的方法等:vm.helloWorld();

要让用户进入 app.js,您可以在脚本标签之间的 JSON 中打印它。您的 app.js 稍后应该可以访问它。例如

<script>
    var user="{{$user}}";
</script>
<script src="app.js" type="text/javascript"></script>

但也许使用 AJAX 请求会更好。