vuex的快速理解,应用

221 阅读1分钟

index.vue

<template>
    <div>{{this.data}}</div>
    <div>{{this.newData}}</div>
    <button @click="handleClick">更新vuex</button>
</template>

<script>
import { mapState , mapMutations , mapGetters } form 'vuex';
export default {
    name:'Index',
    computed: {
        //mapState作用 把 vuex 里的key 映射到当前页面的计算属性中
        ...mapState(['data'])||...mapState({newData:data}),
        ...mapGetters(['dataC'])
    },
    methods:{
        handleClick (data) {
            //存储数据
            //this.$store.dispatch('functionName',data)
            
            //this.$store.commit('functionName',data)
            this.$router.push('/')
            this.functionName(data)
        },
        ...mapMutations(['functionName'])
    }
}
</script>

##store/index.js

const store = new Vuex.Store( {
    computed: Vuex.mapState(state),
    strict: true,//严格模式,正式发布禁用
    //namespaced: true,//分模块时子模块使用 
    state:{ //数据仓库
        data:localStorage.data|| '默认值'
    } 
    getters:{//计算属性
        dataC(state){
            return state.data + '单位'
        }
    }
    actions:{//dispatch调用方法
        functionName(ctx,data){
            ctx.commit('functionName',data)
        }
    },
    mutations:{//commit调用
        functionName (state,data){
            //设置数据仓库数据
            state.data = data
            localStorage.data = data;
        }
    }
});