1. 程式人生 > 程式設計 >如何理解Vue簡單狀態管理之store模式

如何理解Vue簡單狀態管理之store模式

概述

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程式設計客棧3;'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){
      DOYLK
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'
http://www.cppcns.comimport B from './components/B.vue'

export default {
  name: 'App',components: {
    A,B
  }
}
</script>

3. 實現效果

如何理解Vue簡單狀態管理之store模式

可以看到,在 A元件 中顯示的資料,在 B元件 中進行新增和修改,就是程式設計客棧通過資料共享的方式進行資料通訊,簡單的 sDOYLKtore模式 就是這樣的運用方式。

以上就是如何理解Vue簡單狀態管理之store模式的詳細內容,更多關於Vue簡單狀態管理之store模式的資料請關注我們其它相關文章!