[英]Mutation Doesn't Set Value in State
我設置了帶有突變的值,但是它不會更新狀態對象中的值。 它在mutations
對象內創建新變量。
mutations.js:
const mutations = {
setUser(state, user) {
state.user = user; // eslint-disable-line no-param-reassign
},
setToken(state, token) {
state.token = token; // eslint-disable-line no-param-reassign
},
setAuthenticated(state, authenticated) {
state.authenticated = authenticated; // eslint-disable-line
},
};
export default {
mutations,
};
state.js:
const state = {
callingAPI: false,
activeSidebar: true,
searching: '',
authenticated: null,
user: null,
token: null,
userInfo: {
messages: [],
notifications: [],
tasks: [],
},
};
const getters = {
isAuthenticated: (state) => { // eslint-disable-line
return state.authenticated;
},
isActiveSidebar: (state) => { // eslint-disable-line
return state.activeSidebar;
},
};
export default {
state,
getters,
};
store.js:
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state';
import mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
state,
mutations,
},
});
我用commit
函數更新值。 例如: this.store.commit('setAuthenticated', true);
import { mapMutations } from 'vuex';
import store from '../store';
export default {
computed: {
...mapMutations([
'setAuthenticated',
'setUser',
'setToken',
]),
},
store,
login(context, creds) {
context.$http.post(LOGIN_URL, JSON.stringify(creds)).then(
(response) => {
if (response.status === 200) {
const bodyText = response.bodyText.split('\n');
const token = bodyText[0].split(' ');
let redirect = bodyText[1];
redirect = redirect.substring(redirect.indexOf('[') + 1, redirect.indexOf(']'));
this.store.commit('setToken', token[1]);
this.store.commit('setAuthenticated', true);
...........
});
}
它不是應該更新state
對象中的空值,而不是在mutations
對象中創建新變量嗎?
您似乎在濫用模塊。 我假設您實際上並沒有嘗試使用它們。 您還會在state
導入中出現意外的屬性嵌套。
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import {state,getters} from './state';
import mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
state,
getters,
mutations,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.