Vuex简记

107 阅读1分钟

下载: npm i vuex

用法:

// ./store/index.js
import Vue from 'vue'; 
import Vuex from 'vuex'; 
Vue.use(Vuex);
const store = new Vuex.Store({ 
    state: { //静态数据
        name: '张三'
    },
   getters:{
       computedName(state){//state-对应上面的state
           return `纳兰${state.name}`
       }
   },
   mutations:{
       methodName(state,name){//修改state里name的值
           state.name = name
       }
   },
   actions:{//异步的写到这里
        promiseName(myStore,name){
            return new Promise((rs,rj)=>{
                setTimeOut(()=>{
                    myStore.commit('methodName',name)//触发mutation里的methodName
                    rs()
                },20)
            })
        }
   }
}); 

export default store;


// main.js
import store from './store'; // 引入我们前面导出的store对象 
new Vue({ 
    el: '#app', 
    store, // 把store对象添加到vue实例上 
    components: { App }, 
    template: '<App/>' 
});


// App.vue
<template>
    <div>{{name}}</div>
    <div>{{mycomputedName}}</div>
</template>
<script>
import { mapState, mapGetters,mapMutations,mapActions } from 'vuex';//如果要使用解构,需要先引用
    export default {
        async mounted() {
            // 使用this.$store.state.XXX可以直接访问到仓库中的状态
            console.log(this.$store.state.name); 
            console.log(this.name); 
            console.log(this.$store.getters.computedName); 
            console.log(this.computedName);
            this.$store.commit('methodName','关羽')
            this.mymethodName('关羽');//this.methodName('关羽')也可以
            await this.$store.dispatch('promiseName','关羽')
            await this.mypromiseName('关羽')//this.promiseName('关羽')也可以
        },
        computed:{
            ...mapState({myname:name}),//另命名
            ...mapState(['name']),//也可以用本来的命名
            ...mapGetters({mycomputedName:computedName}),
            ...mapGetters({['computedName']),
        },
        methods:{
            ...mapMutation(['methodName']),
            ...mapMutation({mymethodName:methodName}),
            ...mapActions(['promiseName']),
            ...mapActions({mypromiseName:promiseName}),
        }
    }
</script>