国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

如何理解Vue簡單狀態(tài)管理之store模式

瀏覽:2日期:2022-09-29 15:41:06
目錄概述1. 定義 store.js2. 組件使用 store.js3. 實(shí)現(xiàn)效果概述

store 狀態(tài)管理模式的實(shí)現(xiàn)思想很簡單,就是定義一個 store 對象,對象里有 state 屬性存儲共享數(shù)據(jù),對象里還存儲操作這些共享數(shù)據(jù)的方法。在組件中將 store.state 共享數(shù)據(jù)作為 data 的一部分或全部,在對 store.state 對象里的共享數(shù)據(jù)進(jìn)行改變時,必須調(diào)用 store 提供的接口進(jìn)行共享數(shù)據(jù)的更改。

以下以一個簡單 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)效果

如何理解Vue簡單狀態(tài)管理之store模式

可以看到,在 A組件 中顯示的數(shù)據(jù),在 B組件 中進(jìn)行添加和修改,就是通過數(shù)據(jù)共享的方式進(jìn)行數(shù)據(jù)通信,簡單的 store模式 就是這樣的運(yùn)用方式。

以上就是如何理解Vue簡單狀態(tài)管理之store模式的詳細(xì)內(nèi)容,更多關(guān)于Vue簡單狀態(tài)管理之store模式的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Vue
相關(guān)文章:
主站蜘蛛池模板: 石狮市| 资源县| 东乌| 威远县| 镇坪县| 汉寿县| 东至县| 香河县| 冕宁县| 庆阳市| 勃利县| 龙口市| 永寿县| 玛纳斯县| 吐鲁番市| 安岳县| 清丰县| 灌阳县| 黄大仙区| 伊金霍洛旗| 如东县| 西贡区| 锡林浩特市| 邳州市| 江永县| 黔东| 万宁市| 色达县| 广南县| 长沙县| 和政县| 崇文区| 阳曲县| 陈巴尔虎旗| 七台河市| 遂川县| 高台县| 红安县| 海林市| 杭锦后旗| 全椒县|