【发布时间】:2019-11-21 00:09:52
【问题描述】:
我正在使用来自 VueX 的 mapGetters 助手,但我仅在页面的第一次加载时遇到了一些问题,它不是反应式的......
让我告诉你:
触发更改的我的 html 模板:
<input type="number" value="this.inputValue" @change="this.$store.dispatch('setInputValue', $event.target.value)">
我的商店收到了价值
{
state: {
appValues: {
inputValue: null
},
},
getters: {
getInputValue: (state) => {
return state.appValues.inputValue;
},
},
mutations: {
setInputValue(state, value) {
state.appValues.inputValue = value;
},
},
actions: {
setInputValue(context, payload) {
return new Promise((resolve, reject) => {
context.commit('setInputValue', payload);
resolve();
});
},
}
}
然后我的组件监听商店:
import {mapGetters} from 'vuex';
computed: {
...mapGetters({
inputValue: 'getInputValue',
}),
}
watch: {
inputValue: {
deep: true,
immediate: true,
handler(nVal, oVal) {
console.log("inputValue", nVal, oVal);
}
},
}
所以现在,当我第一次加载页面时,我得到了这个 console.log "inputValue" null undefined,这是完全正常的,因为我的商店里什么都没有,它给了我默认值 null。
但现在是奇怪的部分。我开始更改输入值,但我的控制台中没有任何内容。什么都没有动……
然后我重新加载页面并在加载时得到这个 console.log "inputValue" 5 undefined(5 是我之前输入的值)所以你可以看到,当我之前更改输入时,它很好地保持了值在商店中,但计算的值没有自行更新...
现在,当我更改输入的值时,我的控制台日志是这样的 "inputValue" 7 5,所以它可以像我希望的那样从一开始就工作......
我做错了什么?为什么在第一次加载时计算值没有反应?
感谢您的回答...
【问题讨论】:
标签: javascript vue.js vuex store vue-reactivity