我只是想弄清楚它是如何工作的 . 我使用路由器,我有一个父元素和一个子元素 . 在孩子中,我在子组件中有这个简单的HTML元素:<button @click="consoleLog">consoleLog</button>
main.js上的商店有这个动作:
export const store = new Vuex.Store({
state: {
userName: undefined,
password: undefined,
authenticated: false
},
mutations: {
changeUserNameMutation(state, userName) {
state.userName = userName;
},
changePasswordMutation(state, password) {
state.password = password;
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticatedMutation(state, isAuthenticated) {
state.authenticated = isAuthenticated;
}
},
actions: {
changeUserName({ commit }, userName) {
commit('changeUserNameMutation', userName);
},
changePassword({ commit }, password) {
commit('changePasswordMutation', password);
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticated({ commit }, isAuthenticated) {
commit('changeAuthenticatedMutation', isAuthenticated);
},
consoleLog({ commit }) {
console.log('sad');
}
}
在main.js中没有更多的东西,只是新的Vue调用,Vue.use()调用和导入 .
在子组件中,我有以下操作:
methods: {
changeUserName(userName) {
store.dispatch('changeUserName', userName);
},
changePassword(password) {
store.dispatch('changePassword', password);
},
login() {
this.axios.get('http://localhost:3050/admin/login')
.then((data) => {
console.log(data);
})
.catch(() => {
console.log(data);
});
},
...mapActions(['consoleLog'])
}
前两个调度工作,但是当我点击consoleLog方法时,它说:Cannot read property 'dispatch' of undefined at VueComponent.mappedAction
我已经尝试了所有其他方式来调用... mapActions(),但不是以某种方式对我这样工作 .
(这是我在Vue的第一天,尝试它是如何工作的)