![](/img/trans.png)
[英]Vuex & VueJS (Do not mutate vuex store state outside mutation handlers)
[英]Watch and mutation in vuejs/vuex
所以我设法从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);
},
谢谢陈以利!!
你的代码无效。 观察者内部的isXActive
是布尔类型(就像你在上面的评论中所说的那样),商店中的styleForX
是样式输入的样式对象类型。 现在,当观察者被触发时,您将布尔类型发送到突变,并且突变将 styleForX 设置为布尔类型。
例如,您应该发送一个样式字符串而不是布尔值
watch: {
isXActive: function() {
this.$store.commit("SET_STYLE_FOR_X", {backgroundColor: "white", zIndex: "51"});
}
}
对象样式类型的示例是{ color: 'red' }
。 这只是 js 对象在这里查看更多信息https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles
在您的手表处理程序中,当您似乎打算调用this.$store.dispatch()
时,您正在调用this.$store.commit
.$store.commit。 commit
运行一个突变。 dispatch
运行一个动作。 您用于从布尔值计算样式的代码在操作中,因此您应该使用dispatch
。
也就是说,没有理由在这里使用操作,因为您没有任何异步代码。 只需将样式字符串的逻辑放在突变中而不是动作中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.