我想在vuex狀態對象中引用一個變量。控制檯日誌顯示整個對象中的變量&值。但是當我嘗試引用對象中的特定變量時,它顯示爲「未定義」?奇怪的Vuex錯誤:「未定義」,(當它顯示在控制檯中定義)?
我試圖從該對象引用state.columnPercentChecked在Vuex行動,像這樣:
checkAndSetColumnPercent (state) {
console.log('CHECK & SET COLUMN PERCENT ')
console.log(state.columnPercentChecked)
console.log(state)
if (state.columnPercentChecked === true) {
console.log('checkAndSetColumnPercent TRUE HIT ')
var colPercent = state.getters('getColumnPercent')
console.log('checkAndSetColumnPercent : colpercent ' + colPercent)
state.commit('CHANGE_INITIAL_PERCENT', colPercent)
}
控制檯日誌顯示對它的引用作爲「未定義」?我在哪裏錯了?
下面是完整的上下文的store.js文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// root state object.
// each Vuex instance is just a single state tree.
const state = {
initialPercent: 100,
columnPercentChecked: false,
pricePoints: [],
optimizePrices: false,
optimizeAbove: null,
startAsset: null,
endAsset: null,
assetPair: null,
exchange: null
}
// mutations are operations that actually mutates the state.
// each mutation handler gets the entire state tree as the
// first argument, followed by additional payload arguments.
// mutations must be synchronous and can be recorded by plugins
// for debugging purposes.
const mutations = {
ADD_PRICE_POINT ({pricePoints}, pricePoint) {
state.pricePoints.push(pricePoint)
},
DELETE_PRICE_POINT ({pricePoints}) {
pricePoints.splice(state.pricePoints, 1)
},
CHANGE_INITIAL_PERCENT ({initialPercent}, newPercent) {
state.initialPercent = newPercent
},
TOGGLE_COLUMN_CHECKED ({columnPercentChecked}) {
state.columnPercentChecked = !columnPercentChecked
}
}
// actions are functions that causes side effects and can involve
// asynchronous operations.
const actions = {
addPricePoint (state, pricePoint) {
state.commit('ADD_PRICE_POINT', pricePoint)
state.dispatch('checkAndSetColumnPercent')
},
changeInitialPercent (state, newPercent) {
state.commit('CHANGE_INITIAL_PERCENT', newPercent)
if (state.columnPercentChecked === true) {
state.commit('TOGGLE_COLUMN_CHECKED')
}
},
toggleColumnPercentChecked (state) {
state.commit('TOGGLE_COLUMN_CHECKED')
state.dispatch('checkAndSetColumnPercent')
},
checkAndSetColumnPercent (state) {
console.log('CHECK & SET COLUMN PERCENT ')
console.log(state.columnPercentChecked)
console.log(state)
if (state.columnPercentChecked === true) {
console.log('checkAndSetColumnPercent TRUE HIT ')
var colPercent = state.getters('getColumnPercent')
console.log('checkAndSetColumnPercent : colpercent ' + colPercent)
state.commit('CHANGE_INITIAL_PERCENT', colPercent)
}
}
}
// getters are functions
const getters = {
getColumnPercent ({ pricePoints }) {
var l = pricePoints.length
if (l > 1){
return 100/l
}
return 100
}
}
// A Vuex instance is created by combining the state, mutations, actions,
// and getters.
export default new Vuex.Store({
state,
getters,
actions,
mutations
})
看起來你正在登錄的對象是'state',具有'state'屬性。所以,'state.state.columnPercentChecked'。 TBH我認爲你想在'checkAndSetColumnPercent({state})中解構函數參數中的狀態' – Bert