Vuex的个人理解

290 阅读2分钟

Vuex 四个属性

state,mutations,getters,actions(先说前面两个)
//先新建store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
const store = new Vuex.Store({ //声明一个store实例
    state,//数据 ---->state声明看1.state
    mutations,//方法
    getters,//比如我们现在要对store.js文件中的count进行一个计算属性的操作,就是在它输出前,给它加上100.我们首先要在store.js里用const声明我们的getters属性。
})

1.state (相当于参数/对象)-辅助函数(mapState)

//store.js  定义一个count参数
const state = {
    count:1
}

2.mutations(相当于方法,vue中的methods)-辅助函数(mapMutations)

//store.js 定义add和reduce方法
const mutations = {
    add(state,n){
        state.count+=n;
    },
    reduce(state){
        state.count-=1;
    },
}

3.getters(相当于计算属性,vue中的computed)-辅助函数(mapGetters)

const getters = {
    count(state){
        return state.count +=100;
    }
}

4.actions(和mutations差不多,mutations为同步,actions为异步)(mapActions)

  • actions不能直接单独修改state里面的值,需要用到mutations来间接修改。
//store.js
mutations: {
    INCREMENT(state,val){
        state.val = val //输出为‘我是值’
    }
}
actions: { //存放异步方法
    incrementAsync( {commit} ){
      return new Promise((resolve,reject) =>{
        setTimeout(()=>{
          commit('increment',val)//increment是mutations里面的方法名
          resolve()
        },1000)
      })
    }
  }
//.vue
methods:{
    add(){
            this.incrementAsync({'我是值'})
          },
    ..mapActions['incrementAsync']
}
<!--最后新建count.vue-->
<template>
    <div class="vuex">
        <h2>{{msg}}</h2>
        <hr/>
        <h3>{{count}}</h3>
        <div>
            <button @click="add(2)">+</button>
            <button @click="reduce()">-</button>
        </div>
        <div>
            <span>改变count内的值</span>
            <button @click="changeCount()">变为666</button>
        </div>
    </div>
</template>
<script>
    import {mapState,mapMutations,mapGetters } from 'vuex';//引入vuex的辅助函数  mapState,mapGetters放在couputed中;magMutations放在methods中
    export default{
        data(){
            return{
                msg:'Hello Vuex',

            }
        },
        created(){
            //console.log(18,this.$store);

        },
        methods:{
            ...mapMutations(['add','reduce']),
            changeCount(){
                console.log(32,this.count);
            }
        },
        computed:{
            // 使用对象展开运算符将此对象混入到外部对象中
            ...mapState(['count']),
            //...mapGetters(["count"])
        }

    }
</script>

*注意事项

要改变state内参数的值,只能在mutations中调用方法改变。

由于页面刷新之后,数据就没了,要本地存储下

//在页面加载时读取localStorage里的状态信息
        localStorage.getItem("vuex_store_second") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("vuex_store_second"))));
        //在页面刷新时将vuex里的信息保存到localStorage里
        window.addEventListener("beforeunload",()=>{
            localStorage.setItem("vuex_store_second",JSON.stringify(this.$store.state))
        });

Vuex 第五个属性模块

  • 文档
  • 这里就介绍辅助函数在modules中的用法

1、maptstate

import {mapState} from 'vuex' 

computed: {
            ...mapState({
                vuexModule: state => state.a.age // 取得是a模块内的age值  this.age就可以直接访问
            })
        },

2、mapMutations

  • namespaced属性 - 下面摘自官网

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

    import {mapMutations} from 'vuex'
    methods: {
    	//namespaced 为false时	
        ...mapMutations(['setAge']) //直接this.setAge映射  this.$store.commit...
        //namespaced 为true时
        //方式1
        ...mapMutations('user',['test'])//user为模块,test为mutations内方法
        //方式2 别名模式
        ...mapMutations({
          test1: 'user/test1'
        })
    }

防止vuex刷新丢失的插件

  • vuex-persistedstate