【发布时间】:2019-10-30 18:23:28
【问题描述】:
Vue/Vuex 初学者在这里。有没有办法在 Vuex 中动态设置初始状态?我有一个名为 is_here 的布尔状态(true 如果存在成员),我想在设置之前使用条件语句动态检查其值。
如果我尝试编译如下代码,则会返回此错误:TS2564: Property 'is_here' has no initializer and is not definitely assigned in the constructor.
import { Action, Module, Mutation, VuexModule, getModule } from 'vuex-module-decorators';
export interface IMemberState {
is_here: boolean;
}
@Module({dynamic: true, store, name: 'member', namespaced: true})
class Member extends VuexModule implements IMemberState {
public is_here: boolean // The app expects me to set true or false here
}
如果我将初始化程序的默认值设置为true 或false,则应用程序编译正确。但是,如果我更改状态(假设从 true 到 false)并刷新页面,状态将恢复为 true(基于此布尔值呈现不同的按钮,因此我可以看到它已恢复为true)。
public is_here: boolean = true
我想做的是在设置is_here 状态之前进行 API 调用并检查某些事情。我写了一个@Action 来进行必要的检查。
@Action({})
public async setHereStatus() {
await axios.get('api/member_status').then((response)=>
if(response.here_status) {
// This action returns true or false
)
}
我尝试将这个 @Action 放入而不是硬编码 is_here 的值会起作用,但我收到了这个错误:TS2322: Type '() => Promise<boolean>' is not assignable to type 'boolean'.
public is_here: boolean = this.setHereStatus()
如何在这种情况下动态分配此状态?我应该使用created 或mounted 之类的东西吗?
[更新] 正如@ittus 评论的那样,我应该使用@Mutation 来设置is_here 状态。我一直在做这样的实验。
@Module({dynamic: true, store, name: 'member', namespaced: true})
class Member extends VuexModule implements IMemberState {
public is_here: boolean = false
@Mutation
public SET_HERE_STATUS(status: boolean): void {
this.is_here = status
}
@Action({})
public async setHereStatus() {
await axios.get('api/member_status').then((response)=>
if(response.here_status) {
this.SET_HERE_STATUS(true)
}else {
this.SET_HERE_STATUS(false)
}
}
// In the Vue component where I use this state
created () {
memberModule.setHereStatus()
}
但是,同样的问题仍然存在;如果我刷新页面,或关闭窗口并再次访问相同的 URL,状态将被重置。我不知道我的created 钩子是否正常工作。
【问题讨论】:
-
if I refresh the page, or close the window and access the same URL again, the state is reset.-> Vuex 不会自动保持状态。如果您想在页面重新加载时保持状态,则需要定期存储状态,例如在本地存储中。有插件。 -
我在question 中读到了这一点,所以我正在研究它。就我而言,当我正确配置
created挂钩时,即使我刷新或重新打开页面,状态也会持续存在。不知道什么样的情况需要使用localStorage...有明显的区别吗?
标签: typescript vue.js state vuex