Vuex

/

Vue 状态

Vuex 介绍

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

Vuex 文档

Vuex 基本使用

1)安装 vuex 依赖包

npm install vuex --save

2)导入 vuex 包

import Vuex from 'vuex'

Vue.use(Vuex);

3)创建 store 对象

const store = new Vuex.Store({
   // state 中存放全局共享数据 
   state:{count:0} 
});

4)将 store 对象挂载到 vue 实例中

new Vue({
    el:'#app',
    render:h -> h(app),
    router,
    // 将创建的共享数据对象,挂载到 Vue 实例中,所有的组件就可以直接通过 store 中获取全局共享数据
    store
});

核心概念

state

所有共享的数据都需要存放到 Store  state 中。

组件访问 State 数据的方式:

1)方式一:

this.$store.state.全局数据名称;    

2)方式二:

// 从 vuex 中导入 mapState 函数
import {mapState} from 'vuex'
// 将全局数据映射为当前组件的计算属性
computed:{
    ...mapState(['count']);
}    

Mutation

Mutation 函数用于变更 Store 中的数据,不能执行异步操作:

1)在 Store  mutations 中申明方法

const store = new Vuex.store({
    state:{
      count:0  
    },
    mutations:{
        add(state){
            state.count++;
        },
        addN(state,step){
            state.count+=step;
        }
    }
});    

2)在组件中调用 Mutation 方法

方式一:

methods:{
    handlel(){
        this.$store.commin('add');
        this.$store.commin('addN',3);
    }
}

方式二:

// 1.从 vuex 中按需导入 mutations 函数
import {mapMutations} from 'vuex'
// 2.将指定的 mutations 函数映射为当前组件的 methods 函数
methods:{
    ...mapMutations(['add','addN'])
}    

Action

Action 用于处理异步任务,但是如果需要变更数据也需要间接调用 Mutation 函数。

1)申明方法

const store = new Vuex.store({
    state:{
      count:0  
    },
    mutations:{
        add(state){
            state.count++;
        }       
    }
    actions:{
        addAsync(context){
            // 延时一秒自增
            setTimeount(() =>{
                context.commit('add')
            },1000);
        },
         addNAsync(context,step){
            // 延时一秒自增
            setTimeount(() =>{
                context.commit('addN',step)
            },1000);
        }
    }
}); 

2)组件调用 actions 函数

方式一:

methods:{
    handlel(){
        this.$store.dispatch('addAsync');     
        this.$store.dispatch('addNAsync',3);     
    }
}

方式二:

// 从 vuex 中按需导入 mapActions 函数
import {mapActions} from 'vuex'
    
// 将指定的 actions 函数映射为当前组件的 methods 函数
methods:{
    ...mapActions(['addAsync','addNAsync'])
}    

Getter

Getter 用于对 Store 中的数据进行加工处理形成新的数据。

1)申明方法

const store = new Vuex.store({
    state:{
      count:0  
    },
   getters:{
       showCount(state){
           return state.count;
       }       
   }
}); 

2)组件调用 getter 函数

方式一:

{{this.$store.getters.showCount}}     

方式二:

// 从 vuex 中导入 mapGeters 
import {mapGetters} from 'vuex'
    
// 将指定的 getter 函数映射为当前组件的 computed 函数
computed:{
    ...mapGetters(['showNum'])
}

转载请注明作者和出处,并添加本页链接。
原文链接: //106.12.72.178/18.html