【发布时间】:2020-05-23 15:49:20
【问题描述】:
所以我设法从state 中找到了watch 一个元素,但我还想从状态更新一个元素。
这是我尝试过的,但它不起作用:
<template>
<input :style="styleForX" ... />
</template>
// script in template file :: isXActive returns focus input = true/false
watch: {
isXActive: (isXActive) => {
console.log(123);
this.$store.commit("SET_STYLE_FOR_X", isXActive);
},
},
computed: {
...mapGetters([
"styleForX",
]);
// state.js
export default state = {styleForX: ""}
// getters.js
styleForX: (state) => {
return state.styleForX;
},
// action.js
SET_STYLE_FOR_X({commit}, isXActive) {
const style = isXActive? {backgroundColor: "white", zIndex: "51"} : "";
commit("SET_STYLE_FOR_X", style);
},
// mutation.js
SET_STYLE_FOR_X(state, styleForX) {
state.styleForX= styleForX;
}
每个 js 文件都有export default 语句。
知道我应该如何让它工作吗?
- 更新:
将代码更改为:
watch: {
isXActive: () => {
this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
},
但还是不行。
我得到this 为undefined,所以我得到这个错误:
Error in callback for watcher "isXActive": "TypeError: Cannot read property '$store' of undefined" found in ...
- 更新 - 我把它改成了这个,这工作。但是,如果有人知道如何使第一个版本工作,请发表评论。谢谢!
created() {
this.$store.watch(
() => this.$store.state.isXActive,
() => {
this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
}
);
}
- 更新 - 因为焦点没有移除样式,所以我再次将其更改为:
created() {
this.$store.watch(
() => this.$store.state.isXActive,
() => {
this.$store.dispatch("SET_STYLE_FOR_X", isXActive);
}
);
}
// action.js
SET_STYLE_FOR_X({commit}, isXActive) {
const style = isXActive? {backgroundColor: "white", zIndex: "51"} : "";
commit("SET_STYLE_FOR_X", style);
},
- 更新 - 最终结果
watch: {
isXActive() {
this.$store.commit("SET_STYLE_FOR_X", this.$store.state.isXActive);
},
谢谢陈立!!
【问题讨论】:
-
我修正了我的答案。如果您需要访问
this,请不要在观察者中使用箭头功能。
标签: javascript vue.js vuex mutation