【发布时间】:2021-11-03 11:07:57
【问题描述】:
使用(使用 vuex 操作)获取数据、获取数据并将第一项设置为选定选项的正确方法是什么?
我现在得到的是一个带有角色选择框的AddUser 表单。在创建的函数中,我使用 vuex 调用 fetchRoles 函数从后端获取可用角色。我创建了一个计算属性 roles 以从商店中取回角色。最后,我想要一个本地 selectedRole 变量,默认为第一个角色。
<script>
export default {
created() {
this.$store.dispatch('roles/fetchRoles');
},
computed: {
roles() {
return this.$store.getters['roles/roles'];
},
},
data() {
return {
selectedRole: this.roles[0],
};
},
};
</script>
因为在计算的this.roles[0] 未定义之前数据正在运行。我可以将代码更改为this.roles.length > 0 ? this.roles[0] : null,但当角色最终可用时,变量不会更新。一个可能的解决方案是使用 watch 属性,但我觉得这个概念必须有更好的方法。
额外代码
fetchRoles 操作
export async function fetchRoles(context) {
try {
if (context.state.roles.length === 0) {
const response = await axios.get('roles');
const roles = response.data.roles;
return await context.commit('setRoles', roles);
}
} catch (error) {
console.log(error);
return error;
}
}
setRoles 突变
export function setRoles(state, roles) {
state.roles = roles;
}
角色获取者
export function roles(state) {
return state.roles;
}
【问题讨论】: