寫在前面
狀態管理也就是數據狀態管理,vue 應用程序的各組件之間經常需要進行通信,除了 v-on、EventBus 等通信方式外,可以采用數據共享的方式進行通信。這種簡單的數據共享模式就是 store 模式。
Vue 官網有對簡單狀態管理的介紹,詳看 Vue 狀態管理
store 狀態管理模式的實現思想很簡單,就是定義一個 store 對象,對象里有 state 屬性存儲共享數據,對象里還存儲操作這些共享數據的方法。在組件中將 store.state 共享數據作為 data 的一部分或全部,在對 store.state 對象里的共享數據進行改變時,必須調用 store 提供的接口進行共享數據的更改。
以下以一個簡單 todo-list demo 來介紹 store 狀態管理模式
1. 定義 store.js
//store.js
export 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模式 就是這樣的運用方式。