I am pulling my hair out over this. I am a Vue noob and am trying to build a User Selector.
The User Selector component is a child component that is supposed to display all users in a then I have an @change handler to update the currentUser variable in the vuex store.
I think I am using actions and mutations correctly but for some reason it won't set the currentUser to the payload.
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>
and my store.js is the following:
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);
}
}
});
Can someone please let me know what I am doing wrong? If I console.log the payload in setCurrentUser in mutations, it is correctly passing the new user key however after calling
state.currentUser = payload
the value of the currentUser in state remains as its default, which is 0. When I debug with with Vue dev tool, I can also see that the currentUser in the state remains unchanged.
Please help!
I think there is conflict between v-model
and @change
handle. Please try changing v-model to :value
and remove get set in computed:
<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;
},
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.