Vuex中的States、Mutations、Actions、Getters、Modules、Plugins的作用(推荐使用版本)

目录

一、State

二、Mutations

三、Actions

四、Getters

五、Modules


前提:state.js要引入,

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

 下面我都省略了

一、State

所有共享数据都放到Store的state中存储

const store = new Vuex.Store({
    state: { count: 0 }
})

访问:

<template>
    <div>
        <h3>当前的值为{
   
   { this.$store.state.count }}</h3>//this可以省略
    </div>
</template>

二、Mutations

作用:修改Vuex中的全局数据

1、只能通过Mutation变更Store中的数据

2、操作有点繁琐,但可以集中监控所有数据变化

定义mutations:

const store = new Vuex.Store({
    state: { count: 0 },
    mutations:{ 
        add(state, step) {//参数1: 上面的state  参数2: 组件传过来的参数
            state.count += step
        }
    }
})

组件中触发mutations:

methods: {
    handle() {
        this.$store.commit('add', 3)//commit的作用是调用某个mutation函数
                                    //参数1: 调用mutation函数里面的方法的方法名
                                    //参数2: 传过去的参数
    }
}

三、Actions

actions用于处理异步任务 例如: 计时器

如果通过异步操作变更数据 , 必须通过actions,而不能通过mutations

但是Action还是要通过触发Mutation的方式间接更改数据

定义actions:

const store = new Vuex.Store({
    state: { count: 0 },
    mutations: { 
        addN(state, step) {//参数1: 上面的state  参数2: 组件传过来的参数
            state.count += step
        }
    },
    actions: {
        addNAsyc (context, step) {//参数1:固定写法  参数2:组件传过来的参数
            setTimeout(() => {
                context.commit('addN', step)//调用mutation的addN()
            }, 1000)
        }
    }
})

触发actions:

mathods: {
    handle() {
        this.$store.dispatch('addNAsync', 5)//参数1: Action里面的方法名
                                            //参数2: 传进Action的参数
    }
}

四、Getters

作用:Getter可以对store中的数据进行加工处理形成新数组

(1).Getter可以对store中已有的数据加工处理之后形成新的数据(类似vue的计算属性)

(2).Store中数据发生关系, Getter的数据也会跟着变化

定义getters:

const store = new Vuex.store({
    state: {
        count: 0
    },
    getters: {
        showNum: state => {
            return '当前数量为[' + state.count + ']'
        }
    }
 
})

 触发getters:

<h3>{
   
   { this.$store.getter.showNum }}</h3>

五、Modules

点击链接

六、Plugins

实现数据持久化

点击链接

猜你喜欢

转载自blog.csdn.net/qq_52421092/article/details/130477254