Vuex

2020-10-24  本文已影响0人  笨灬蛋_a210

关于VueX

Vuex 是一个专为 Vue.js 应用程序开发的状态管理工具
大型项目使用为解决组件之间传递数据

之前处理方法:

vueX的作用

  1. vuex能够保存全局数据,供整个应用使用
  2. vuex保存的数据是响应式的
  3. vuex保存的数据可以跟踪状态的变化

使用步骤

  1. 安装
npm install vuex –save
  1. 创建对象 ./src/store/index.js下
//引入vueX
import Vuex from 'vuex'

//把vueX安装到Vue里
Vue.use(Vuex)

export default new Vuex.Store({
    state:{},
    getters:{},
    mutations:{},
    actions:{}
})
  1. 将vueX.store对象植入到vue的根属性 ./src/main.js
import store from './store'

new Vue({
    el: '#app',
    store
})
  1. 组件获取数据
//模板里:
$store.state.id
//脚本里
this.$store.state.id

vueX的核心概念:

04185834_TAxe.png
state : 数据仓库 ,存储所有的 共享数据,相当于vue组件里的data 存放状态
export default new VueX.Store({
    state:{
        age:12,
        isAdult:"未成年",
        isAllowMarry:false
    }
    ......
});


<!--获取-->
{{$store.state.age}}
{{$store.state.isAdult}}
{{$store.state.isAllowMarry?"可以结婚了":"不要着急,再等等"}}




//对state对象中添加一个age成员
Vue.set(state,"age",15)

//将刚刚添加的age成员删除
Vue.delete(state,'age')
Getter : 在state的基础上派生的数据, 相当于vue组件里 computed 加工state成员给外界

Getters中的方法有两个默认参数

export default new VueX.Store({
    state:{
        age:12,
    },
    getters:{
        ageChina:state=>{
            let shi = parseInt(state.age/10); //1
            let ge = state.age%10;//2
            let str = "";
            switch(shi){
                case 1:str='一';break;
                case 2:str='二';break;
            }
            return str;
        }
    }
});
//获取
{{$store.getters.ageChina}}
Mutation:修改state的数据时,用mutation,这与跟踪状态 有关系 模块化状态管理

mutations方法都有默认的形参:

export default new VueX.Store({
    state:{
        age:12,
        isAdult:"未成年",
        isAllowMarry:false
    },
    // mutations:是跟踪状态。这里面只能有同步代码
    mutations:{
        incAge(state,num){
        state.age+=num;
    }
});
Action:解决mutation里只能有同步代码的问题action里可以有异步代码

Actions中的方法有两个默认参数

actions:{
    aEdit(context,payload){
        setTimeout(()=>{
            context.commit('incAge',payload)
        },2000)
    }
}
提交mutation(如果有异步就在action提交,如果没有异步就在组件里提交)
//组件里提交
$store.commit('incAge',num);
$store.commit('incAge',{ num:111 });
$store.commit({
    type:'incAge',
    payload:{
    age:15,
    sex:'男'
}
});


//action提交
$store.dispatch("incAge",num)
Action和mutation的区别

关于Module

如果项目大的话全局数据太多会混乱,可以分类处理,分模块

./src/store/moduleA.js

export default {
    state: {count:1}, 
    mutations: { ... }, 
    actions: { 
         incCount(context){
            console.log("moduleA的action");
            setTimeout(()=>{
                context.commit("incCount");
            },2000);
        }
    }, 
    getters: { ... } 
}
                                                   
./src/store/moduleB.js

export default {
    state: {count:2}, 
    mutations: { ... }, 
    actions: { 
         incCount(context){
            console.log("moduleB的action");
            setTimeout(()=>{
                context.commit("incCount");
            },2000);
        }
    }, 
    getters: { ... } 
}

在总的store里包含所有的模块:

import Vue from "vue";
import vueX from "vuex";
import moduleA from "./moduleA";
import moduleB from "./moduleB";

Vue.use(vueX);

export default new vueX.Store({
    modules:{
        moduleA:moduleA,
        moduleB:moduleB
    }
    //简写:
    modules:{
        moduleA,moduleB
    }
});

使用

store.state.moduleA.count // -> moduleA 的状态
store.state.moduleB.count // -> moduleB 的状态
模块(Module)里的命名空间(namespaced:true)

模块具有更高的封装度和复用性,你可以通过添加 namespaced: true 的方式使其成为带命名空间的模块。当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名。

export default {
    namespaced:true,
    state:{
        count:1
    },
    mutations:{
    },
    actions:{        
    }
}

派发action时,加上模块名

this.$store.dispatch('moduleA/incCount');

vuex中mapState、mapMutations、mapAction的理解
https://blog.csdn.net/wangguoyu1996/article/details/80573113

上一篇 下一篇

猜你喜欢

热点阅读