[英]How can I reactively update a value in a component from a store value?
根据此处的文档,我有两个组件和一个基本商店: https ://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch。
我想这样做,以便当我输入输入时,使用存储更新不同组件中的值。
这里的基本示例。
应用程序.vue
<template>
<div id="app">
<h1>Store Demo</h1>
<BaseInputText /> Value From Store: {{ test }}
</div>
</template>
<script>
import BaseInputText from "./components/BaseInputText.vue";
import { store } from "../store.js";
export default {
// This should reactively changed as per the input
computed: {
test: function() {
return store.state.test;
}
},
components: {
BaseInputText
}
};
</script>
BaseInput.vue
<template>
<input type="text" class="input" v-model="test" />
</template>
<script>
import { store } from "../store.js";
export default {
data() {
return {
test: store.state.test
};
},
// When the value changes update the store
watch: {
test: function(newValue) {
store.setTest(newValue);
}
}
};
</script>
store.js
export const store = {
debug: true,
state: {
test: "hi"
},
setTest(newValue) {
if (this.debug) console.log("Set the test field with:", newValue);
this.state.test = newValue;
}
};
我想这样做,以便当我在输入中键入一个字符串时,App.vue 中的test
变量会被更新。 我试图了解商店模式是如何工作的。 我知道如何使用道具。
我这里也有一份工作副本: https ://codesandbox.io/s/loz79jnoq?fontsize=14
更新
2.6.0+
使用Vue.observable
(在 2.6.0+ 中添加)使 store 响应式
store.js
import Vue from 'vue'
export const store = Vue.observable({
debug: true,
state: {
test: 'hi'
}
})
BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
return {
state: store.state
};
},
2.6.0之前
store.js
import Vue from 'vue'
export const store = new Vue({
data: {
debug: true,
state: {
test: 'hi'
}
}
})
BaseInputText.vue
<input type="text" class="input" v-model="state.test">
...
data() {
return {
state: store.state
};
}
旧答案
来自文档However, the difference is that computed properties are cached based on their reactive dependencies
。 商店没有反应
改成
应用程序.vue
data() {
return {
state: store.state
};
},
computed: {
test: function() {
return this.state.test;
}
},
它看起来很糟糕,但我没有看到另一种让它发挥作用的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.