根据这里的文档,我有两个组件和一个基本存储:https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch。
我想这样做,以便在我输入输入时,使用商店更新不同组件中的值。
这里的基本示例。
App.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>
商店.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+ 中添加)
商店.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 之前
商店.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
. 存储不是反应性的
更改为
App.vue
data() {
return {
state: store.state
};
},
computed: {
test: function() {
return this.state.test;
}
},
它看起来很糟糕,但我看不到另一种使其工作的方法