【发布时间】:2019-08-16 03:33:12
【问题描述】:
根据此处的文档,我有两个组件和一个基本存储:https://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>
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
【问题讨论】:
-
如果你想更新
store的状态,你应该使用mutations。直接修改 store 是一种反模式,你会看到一个关于它的控制台警告。 -
这适用于文档中引用的商店模式。抱歉,vuex 标签有点误导。
标签: javascript vue.js vuejs2