何时初始化 vue 和 vuex 状态
when to initialize vue and vuex state
最近设计网页,用户分成"user"/"admin"两个角色登录。
不同的角色会登录同一个页面,但会看到不同的按钮和功能。
MainPage.vue
是容器,所以我调用 ajax “/init” 来获取用户信息,然后提交到 Vuex 存储。
那么Content.vue
就是MainPage.vue
里面的子页面。它会通过 $store.state.user
消息显示不同的按钮。
不过,我想根据用户的角色在mounted
阶段调用不同的apiContent.vue
。
但是在这个阶段被称为“/init”的ajax提交的角色不会准备好。
整体流量为
// MainContent.vue
beforeCreate: async function () {
await axios.post('/init').then(response => {
if(response && response.data && response.data.data){
this.$store.commit("login", response.data.data)
}
})
}
// Content.vue
mounted: async function() {
try {
console.log(this.$store, this.$store.state.user, this.$store.getters.isAdmin)
// no value here
}
我检查了 vue 组件生命周期,发现父组件的 beforeCreate
会在子组件的 mounted
之前被调用。
即使是异步函数,生命周期方法也会按顺序调用吗?
我应该如何解决这个问题?
谢谢
您可以延迟 Content
组件的初始化,直到 user
状态在 Vuex 中可用,方法是将 v-if
指令附加到 Content
组件。只需确保在 Vuex 状态下用 null
初始化 user
。
<!-- MainPage.vue -->
<template>
<Content v-if="$store.state.user" />
</template>
现在 this.$store.state.user
以及依赖于它的所有内容都应该可以从 Content
组件的 mounted
生命周期挂钩中获得。
您的组件生命周期将不是处理这种情况的可靠方式,因为您正在使用异步调用来获取用户数据。我建议显示加载状态叠加层并使用 mapGetters
访问商店。这将为您提供一种反应机制,让您知道用户数据何时可用。以下是单个文件组件的总体思路:
computed: {
...mapGetters({
getLoggedInUser: 'GET_LOGGED_IN_USER',
getIsUserAdmin: 'GET_IS_USER_ADMIN',
})
}
....
<template>
<content-overlay v-if="!getLoggedInUser">
Loading...
</content-overlay>
....
<button v-if="getIsUserAdmin">Admin Button</button>
<button v-if="!getIsUserAdmin">Regular User Button</button>
</template>
最近设计网页,用户分成"user"/"admin"两个角色登录。
不同的角色会登录同一个页面,但会看到不同的按钮和功能。
MainPage.vue
是容器,所以我调用 ajax “/init” 来获取用户信息,然后提交到 Vuex 存储。
那么Content.vue
就是MainPage.vue
里面的子页面。它会通过 $store.state.user
消息显示不同的按钮。
不过,我想根据用户的角色在mounted
阶段调用不同的apiContent.vue
。
但是在这个阶段被称为“/init”的ajax提交的角色不会准备好。
整体流量为
// MainContent.vue
beforeCreate: async function () {
await axios.post('/init').then(response => {
if(response && response.data && response.data.data){
this.$store.commit("login", response.data.data)
}
})
}
// Content.vue
mounted: async function() {
try {
console.log(this.$store, this.$store.state.user, this.$store.getters.isAdmin)
// no value here
}
我检查了 vue 组件生命周期,发现父组件的 beforeCreate
会在子组件的 mounted
之前被调用。
即使是异步函数,生命周期方法也会按顺序调用吗?
我应该如何解决这个问题?
谢谢
您可以延迟 Content
组件的初始化,直到 user
状态在 Vuex 中可用,方法是将 v-if
指令附加到 Content
组件。只需确保在 Vuex 状态下用 null
初始化 user
。
<!-- MainPage.vue -->
<template>
<Content v-if="$store.state.user" />
</template>
现在 this.$store.state.user
以及依赖于它的所有内容都应该可以从 Content
组件的 mounted
生命周期挂钩中获得。
您的组件生命周期将不是处理这种情况的可靠方式,因为您正在使用异步调用来获取用户数据。我建议显示加载状态叠加层并使用 mapGetters
访问商店。这将为您提供一种反应机制,让您知道用户数据何时可用。以下是单个文件组件的总体思路:
computed: {
...mapGetters({
getLoggedInUser: 'GET_LOGGED_IN_USER',
getIsUserAdmin: 'GET_IS_USER_ADMIN',
})
}
....
<template>
<content-overlay v-if="!getLoggedInUser">
Loading...
</content-overlay>
....
<button v-if="getIsUserAdmin">Admin Button</button>
<button v-if="!getIsUserAdmin">Regular User Button</button>
</template>