问题描述:
进入页面时,先使用dispatch从后端接口获取数据
this.$store.dispatch('getOption', 'a,b,c,d')
然后再使用vuex的getters从store中获取数据
...mapGetters(['optionList'])
最后再使用v-for遍历optionList
<el-select v-model="queryParams" clearable placeholder="请选择选项">
<el-option
v-for="item in optionList['a']"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
这个时候会出现选项加载不出来的现象,选项为无数据
原因分析:
从后端获取数据时间比较长,导致dom被渲染出来了,而数据还没获取到,所以dom渲染时所关联的数据还为空,这就是为什么选项为空,同理,其他使用从接口获取到的数据也可能为空。
解决方法:
在data中定义一个待遍历的对象,然后通过异步函数接收vuex中存储的值,即可。
js代码如下:
...mapGetters(['optionObj'])
async getOption() {
await this.$store.dispatch('getOption', 'a,b,c,d')
this.options= this.optionObj
}
页面代码如下:
<el-select v-model="queryParams" clearable placeholder="请选择选项">
<el-option
v-for="item in options['a']"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>