简体   繁体   English

来自Laravel API的Vuejs全局用户对象

[英]Vuejs Global User Object from Laravel API

I have a small Laravel / VueJS app with single file components and it is a single page application. 我有一个带有单个文件组件的小型Laravel / VueJS应用程序,它是一个单页面应用程序。 I use vue-stash for central state managment. 我使用vue-stash进行中央国家管理。

Here is my store.js 这是我的store.js

export default {
    user: {
        name: null
    }
}

And here is my api call from my dashboard. 这是我的仪表板上的api电话。

<script>
    export default {
        mounted() {
            axios.get('/api/getAuthUser')
                    .then(response => {
                        this.$store.user.name = response.data.name;
                    });
        }
    }
</script>

This works fine and it will set the user name in store to the user name i get from my api call. 这很好用,它会将商店中的用户名设置为我从api调用中获得的用户名。

But if the first visit to my site is not the dashboard then there is no api call and the name is not set in the store. 但是,如果第一次访问我的网站不是仪表板,那么就没有api调用,并且商店中没有设置名称。 But I need that name at different places in my app. 但我在我的应用程序中的不同位置需要该名称。

I don't wont to call my api from every component. 我不会从每个组件中调用我的api。 Is it possible to call the api only once directly from my store? 是否可以直接从我的商店调用api一次? How can I do that or is there any better solution? 我该怎么做?还是有更好的解决方案?

Thanks! 谢谢!

// UPDATE //更新

Is there any way to make a direct call from the store.js? 有没有办法从store.js直接打电话?

export default {
user: {
    name: null
},
ready () {
    axios.get('/api/getAuthUser')
        .then(response => {
            this.user.name = response.data.name;
        });
    }
}

This does not work. 这不起作用。 name is still null 名称仍为空

// Update 2 //更新2

import axios from 'axios'

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};



export default {
    user: {
        name: null
    },
    setUser() {
        axios.get('/api/getAuthUser')
        .then(response => {
        this.user.name = response.data.name;
    });
}}

This is my complete store.js but it seems that setUser() does not get executed. 这是我的完整store.js但似乎setUser()没有被执行。

If you need your user on every page, what about something like this? 如果您在每个页面都需要您的用户,那么这样的事情呢?

new Vue({
   el: "#app",
   mounted: function() {
     // make a request to the api here
   },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM