写在前面
状态管理也就是数据状态管理,vue 应用程序的各组件之间经常需要进行通信,除了 v-on、EventBus 等通信方式外,可以采用数据共享的方式进行通信。这种简单的数据共享模式就是 store 模式。
Vue 官网有对简单状态管理的介绍,详看 Vue 状态管理
store 状态管理模式的实现思想很简单,就是定义一个 store 对象,对象里有 state 属性存储共享数据,对象里还存储操作这些共享数据的方法。在组件中将 store.state 共享数据作为 data 的一部分或全部,在对 store.state 对象里的共享数据进行改变时,必须调用 store 提供的接口进行共享数据的更改。
以下以一个简单 todo-list demo 来介绍 store 状态管理模式
1. 定义 store.js
//store.jsexport const store = {state: {todos: [{text: '写语文作业', done: false},{text: '做数学卷子', done: false}]},addTodo(str){const obj = {text: str, done: false}this.state.todos.push(obj)},setDone(index){this.state.todos[index].done = true}}
2. 组件使用 store.js
//A.vue<template><div class="A">我是 A组件<ul><li v-for="(todo,index) in todos":key="index" :class="todo.done?'done':''" @click="setDone(index)">{{todo.text}}</li></ul></div></template><script>import {store} from '../store/store.js'export default {name: 'A',data(){return store.state},methods: {setDone(index){store.setDone(index)}}}</script><style scoped>.A{background: red;color: white;padding: 20px;}.A li.done{background: green;}</style>
//B.vue<template><div class="B"><div>我是 B 组件,在下方输入框输入任务在 A组件 中添加任务</div><input type="text" v-model="text"><button @click="addTodo">add todo</button></div></template><script>import {store} from '../store/store.js'export default {name: 'B',data(){return {text: ''}},methods:{addTodo(){if(this.text){store.addTodo(this.text)}}}}</script><style scoped>.B{background: yellow;padding: 20px;}</style>
//App.vue<template><div id="app"><A /><B /></div></template><script>import A from './components/A.vue'import B from './components/B.vue'export default {name: 'App',components: {A,B}}</script>
3. 实现效果

可以看到,在 A组件 中显示的数据,在 B组件 中进行添加和修改,就是通过数据共享的方式进行数据通信,简单的 store模式 就是这样的运用方式。
