我正在为此扯头发。我是Vue菜鸟,正在尝试构建用户选择器。
User Selector组件是一个子组件,应该在中显示所有用户,然后我有一个@change处理程序来更新vuex存储中的currentUser变量。
我认为我正确使用了动作和变异,但由于某种原因,它不会将currentUser设置为有效负载。
UserSelector.vue
<template>
<select class="user-selector" v-model="currentUser" @change="handleChange($event)">
<option v-for="user in users" :key="user" :value="user">User {{ user }}</option>
</select>
</template>
<script>
export default {
name: "UserSelector",
methods: {
handleChange(event) {
this.$store.dispatch("setCurrentUser", event.currentTarget.value);
}
},
computed: {
users() {
return this.$store.getters.users;
},
firstUser() {
return this.users[0];
},
currentUser: {
get: function() {
return this.$store.getters.currentUser;
},
set: function(newCurrentUser) {
this.$store.dispatch("setCurrentUser", event.currentTarget.value);
}
}
},
updated() {
const { firstUser } = this;
if (firstUser) {
this.$store.dispatch("setCurrentUser", firstUser);
}
}
};
</script>
和我的store.js如下:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
todos: {},
users: [],
currentUser: 0
},
getters: {
todos(state) {
return state.todos;
},
users(state) {
return state.users;
},
currentUser(state) {
return state.currentUser;
}
},
mutations: {
setTodos(state, payload) {
state.todos = { ...payload };
},
setUsers(state, payload) {
state.users = [...payload];
},
setCurrentUser(state, payload) {
state.currentUser = payload;
}
},
actions: {
setTodos(context, payload) {
context.commit("setTodos", payload);
},
setUsers(context, payload) {
context.commit("setUsers", payload);
},
setCurrentUser(context, payload) {
context.commit("setCurrentUser", payload);
}
}
});
有人可以让我知道我做错了什么吗?如果我用console.log将setCurrentUser中的有效负载进行了突变,则可以正确地传递新的用户密钥,但是在调用
之后state.currentUser = payload
当前状态下的currentUser的值保留为默认值0。当我使用Vue开发工具进行调试时,我还可以看到当前状态下的currentUser保持不变。
请帮助!
答案 0 :(得分:0)
我认为v-model
和@change
句柄之间存在冲突。请尝试将v-model更改为:value
,并删除已计算的get设置:
<select class="user-selector" :value="currentUser" @change="handleChange($event)">
<option v-for="user in users" :key="user" :value="user">User {{ user }}</option>
</select>
computed: {
currentUser: {
return this.$store.getters.currentUser;
},
},