如何理解Vue簡(jiǎn)單狀態(tài)管理之store模式
store 狀態(tài)管理模式的實(shí)現(xiàn)思想很簡(jiǎn)單,就是定義一個(gè) store 對(duì)象,對(duì)象里有 state 屬性存儲(chǔ)共享數(shù)據(jù),對(duì)象里還存儲(chǔ)操作這些共享數(shù)據(jù)的方法。在組件中將 store.state 共享數(shù)據(jù)作為 data 的一部分或全部,在對(duì) store.state 對(duì)象里的共享數(shù)據(jù)進(jìn)行改變時(shí),必須調(diào)用 store 提供的接口進(jìn)行共享數(shù)據(jù)的更改。
以下以一個(gè)簡(jiǎn)單 todo-list demo 來介紹 store 狀態(tài)管理模式
1. 定義 store.js//store.jsexport 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' : @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. 實(shí)現(xiàn)效果
可以看到,在 A組件 中顯示的數(shù)據(jù),在 B組件 中進(jìn)行添加和修改,就是通過數(shù)據(jù)共享的方式進(jìn)行數(shù)據(jù)通信,簡(jiǎn)單的 store模式 就是這樣的運(yùn)用方式。
以上就是如何理解Vue簡(jiǎn)單狀態(tài)管理之store模式的詳細(xì)內(nèi)容,更多關(guān)于Vue簡(jiǎn)單狀態(tài)管理之store模式的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明2. CSS hack用法案例詳解3. ASP 處理JSON數(shù)據(jù)的實(shí)現(xiàn)代碼4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. asp中response.write("中文")或者js中文亂碼問題7. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法
