如何在组件渲染之前在 vuex 中填充商店
How to populate store in vuex before component renders
我正在使用vuex保存一个状态为属性的树结构。
数据是通过 ajax 调用获取的。
问题是页面在状态 属性 中的变量设法填充之前设法呈现。
即
// sth.ts file
state: {
map: {}
},
...
actions: {
getData({ commit }){
axios.get(...).then(... populate map ...).catch(...)
}
}
// sthelse.vue file
<template>
<div>
<h1>Tree structure</h1>
<ul >
<item v-for="child in map[root]"
:key="child.id"
:name="child.name"
:children="child.Children">
</item>
</ul>
</div>
</template>
我用谷歌搜索,但没有找到有用的东西。
有人处理过类似的问题吗?
有什么办法可以做到吗?
在 vuex 状态中存储对已加载地图键的引用,例如:
state: {
map: {},
keysLoaded: []
}
然后在处理数据的突变中将键推送到 keysLoaded
,在您的组件中您可以使用计算的 属性,例如:
showTree () {
return this.$store.state.keysLoaded.includes(this.root)
}
仅当 showTree 为真时才渲染 ul:
<ul v-if="showTree">
我正在使用vuex保存一个状态为属性的树结构。
数据是通过 ajax 调用获取的。
问题是页面在状态 属性 中的变量设法填充之前设法呈现。
即
// sth.ts file
state: {
map: {}
},
...
actions: {
getData({ commit }){
axios.get(...).then(... populate map ...).catch(...)
}
}
// sthelse.vue file
<template>
<div>
<h1>Tree structure</h1>
<ul >
<item v-for="child in map[root]"
:key="child.id"
:name="child.name"
:children="child.Children">
</item>
</ul>
</div>
</template>
我用谷歌搜索,但没有找到有用的东西。 有人处理过类似的问题吗?
有什么办法可以做到吗?
在 vuex 状态中存储对已加载地图键的引用,例如:
state: {
map: {},
keysLoaded: []
}
然后在处理数据的突变中将键推送到 keysLoaded
,在您的组件中您可以使用计算的 属性,例如:
showTree () {
return this.$store.state.keysLoaded.includes(this.root)
}
仅当 showTree 为真时才渲染 ul:
<ul v-if="showTree">