需求
多个组件共享一个共同的状态
- 多个视图可能都依赖同一份状态
- 来自不同视图的交互也可能需要更改同一份状态
方案
简单状态管理
reactive()
在选形式API中,响应式的数据是在data中声明的,在内部,data的返回值队形会通过reactive()这个公开发的API函数转为响应式。可以使用它来创建一个响应式的队形,并在不同组件中导入它:
//store.js
import { reactive } from 'vue';
export const store = reactive({
count : 0,
increment() {
this.count++
}
});
// 组件1.vue
<template>From A: {
{ store.count }}</template>
<script>
import { store } from './store.js'
export default {
data() {
return {
store
}
}
}
</script>
// 组件2.vue
<template>
<button @click="store.increment()">
From B: {
{ store.count }}
</button>
</template>
<script>
import { store } from './store.js'
export default {
data() {
return {