gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:53:35 26 4
gpt4 key购买 nike

我有一个带有单文件组件的小型 Laravel/VueJS 应用程序,它是一个单页面应用程序。我用vue-stash供中央国家管理。

这是我的 store.js

export default {
user: {
name: null
}
}

这是我从仪表板进行的 API 调用。

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

这工作正常,它会将存储中的用户名设置为我从 api 调用中获得的用户名。

但是,如果第一次访问我的网站不是仪表板,则不会有 api 调用,并且不会在商店中设置名称。但我在应用程序的不同位置需要该名称。

我不习惯从每个组件调用我的 api。是否可以直接从我的商店调用 api 一次?我该怎么做或者有更好的解决方案吗?

谢谢!

//更新

有什么办法可以直接从store.js调用吗?

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

这不起作用。名称仍然为空

//更新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;
});
}}

这是我完整的 store.js,但似乎 setUser() 没有被执行。

最佳答案

如果您在每个页面上都需要用户,那么像这样的东西怎么样?

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

关于javascript - 来自 Laravel API 的 Vuejs 全局用户对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42718291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com