Vuex

196 阅读1分钟

1.组件中使用Vuex

1.Vuex提供了store机制从根组件注册到子组件中,需要使用Vue.use(Vuex),然后在组件中可使用this.$store.state访问state

2.不使用store注册,在组件页面导入使用

2.使用modules

app.js

const app={
    state:{
        list:[1,2,3],
        count:1
    },
    getters:{
        length(state){
            return state.list.length
        },
        anotherGetter(state){
            return state.count+1
        }
    },
    mutations:{
        INCREMENT(state){
            console.log('app count increment')
            state.count++
        }
    }
}

export default app;

user.js

import { stat } from "fs";

const user={
    state:{
        name:'Dave',
        status:true,
        list:['good','gentle'],
        count:1
    },
    getters:{
        length(state){
            return state.list.length
        }
    },
    mutations:{
        INCREMENT(state){
            console.log('user count increment')
            state.count++
        },
        ALTER_STATUS(state){
            console.log('user state change')
            state.status=!state.status
        }
    }
}

export default user;

嵌套modules

import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import user from './modules/user'
Vue.use(Vuex)
const store=new Vuex.Store({
    modules:{
        user,
        app
    }
})
export default store

3.在组件中使用state,getter,mutation

import { mapGetters, mapMutations } from "vuex";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App"
    };
  },
  computed: {
    ...mapGetters(["length", "anotherGetter"]),
    aGetter() {
      return this.$store.getters.anotherGetter;
    }
  },
  methods: {
    ...mapMutations({
      increment: "INCREMENT"
    }),
    change() {
      return this.$store.commit("ALTER_STATUS");
    }
  },
  created() {
    this.increment();
    this.change();
  }
};

注意:当嵌套的modules中的getter有同名的时候,控制台会报duplicate getter key异常,但是仍然可以使用同名的getter,会根据在modules中的顺序,使用首次出现的getter

注意:当嵌套的modules中的mutation有同名的时候,会根据在modules中的顺序,依次执行在每个模块中的mutation。 本例子中,打印:

user count increment
app count increment
user state change