如何理解Vue简单状态管理之store模式

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何理解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&#63;'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模式 就是这样的运用方式。

以上就是如何理解Vue简单状态管理之store模式的详细内容,更多关于Vue简单状态管理之store模式的资料请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的如何理解Vue简单状态管理之store模式全部内容,希望文章能够帮你解决如何理解Vue简单状态管理之store模式所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:storevue