如何理解Vue簡單狀態(tài)管理之store模式
概述
store 狀態(tài)管理模式的實現(xiàn)思想很簡單,就是定義一個 store 對象,對象里有 state 屬性存儲共享數(shù)據(jù),對象里還存儲操作這些共享數(shù)據(jù)的方法。在組件中將 store.state 共享數(shù)據(jù)作為 data 的一部分或全部,在對 store.state 對象里的共享數(shù)據(jù)進行改變時,必須調(diào)用 store 提供的接口進行共享數(shù)據(jù)的更改。
以下以一個簡單 todo-list demo 來介紹 store 狀態(tài)管理模式
1. 定義 store.js
//store.js export const store = { state: { todos: [ {text: '寫語文作業(yè)', done: false}, {text: '做數(shù)學(xué)卷子', 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 組件,在下方輸入框輸入任務(wù)在 A組件 中添加任務(wù) </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. 實現(xiàn)效果
可以看到,在 A組件 中顯示的數(shù)據(jù),在 B組件 中進行添加和修改,就是通過數(shù)據(jù)共享的方式進行數(shù)據(jù)通信,簡單的 store模式 就是這樣的運用方式。
以上就是如何理解Vue簡單狀態(tài)管理之store模式的詳細內(nèi)容,更多關(guān)于Vue簡單狀態(tài)管理之store模式的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解vue2.0 transition 多個元素嵌套使用過渡
這篇文章主要介紹了詳解vue2.0 transition 多個元素嵌套使用過渡,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06vue 路由懶加載中給 Webpack Chunks 命名的方法
這篇文章主要介紹了在 vue 路由懶加載中給 Webpack Chunks 命名的方法,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04詳解vue-router 2.0 常用基礎(chǔ)知識點之router.push()
本篇文章主要介紹了vue-router 2.0 常用基礎(chǔ)知識點之router.push(),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05vue展示dicom文件醫(yī)療系統(tǒng)的實現(xiàn)代碼
這篇文章主要介紹了vue展示dicom文件醫(yī)療系統(tǒng)的實現(xiàn)代碼,非常不錯,具有一定的參考借鑒加載,需要的朋友可以參考下2018-08-08vue使用GraphVis開發(fā)無限拓展的關(guān)系圖譜的實現(xiàn)
本文主要介紹了vue使用GraphVis開發(fā)無限拓展的關(guān)系圖譜,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08Vue項目中實現(xiàn)ElementUI按需引入過程解析
這篇文章主要介紹了Vue項目中實現(xiàn)ElementUI按需引入,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05