vuex的五个属性及使用方法

admin 38 0

Vuex的五个属性及使用方法

Vuex是Vue.js的状态管理模式和库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化,以下是Vuex的五个重要属性及其使用方法:

1. state:一个纯对象

state是Vuex中最为核心的属性,它是一个纯对象,用于存储应用程序的状态,在Vuex中,所有的状态都集中在这个对象上,方便管理和维护,你可以在组件中通过`this.$store.state`来访问这个对象。

使用方法:

// 在store中定义state
const store = new Vuex.Store({
  state: {
    count: 0
  }
});

// 在组件中访问state
computed: {
  doubleCount() {
    return this.$store.state.count * 2;
  }
}

2. getter:对state的计算操作

getter是对state的计算操作,类似于Vue组件中的computed属性,它可以根据state中的数据进行计算,并返回一个新的值,在Vuex中,getter是可选的,但它在处理复杂的逻辑时非常有用。

// 在store中定义getter
const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
});

// 在组件中访问getter
computed: {
  doubleCount() {
    return this.$store.getters.doubleCount;
  }
}

3. mutation:修改state的唯一途径

mutation是修改state的唯一途径,类似于Vue组件中的methods属性,它是一个同步函数,用于直接修改state中的数据,在Vuex中,mutation必须是同步函数,以确保状态的一致性。

// 在store中定义mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

// 在组件中调用mutation
methods: {
  incrementCount() {
    this.$store.commit('increment');
  }
}

4. action:类似于mutation,可以包含任意异步操作

action类似于mutation,可以用来修改state中的数据,与mutation不同的是,action可以包含任意异步操作,如API调用等,在Vuex中,action的使用场景比mutation更广泛。

```javascript

// 在store中定义action

const store = new Vuex.Store({

state: {

count: 0

},

actions: {

incrementIfOdd({ commit, state }) {

if ((state.count + 1) % 2 === 0) {

commit('increment'); // 调用mutation来修改state中的数据

} else { // 否则执行其他操作或返回错误信息等处理逻辑... } } } } }); }); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); })); // 在组件中调用action methods: { incrementIfOdd() { this.$store.dispatch('incrementIfOdd'); } }, // 或者在模板中使用 `this.$store.dispatch('incrementIfOdd')` 来触发这个 action。 } }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); }); // 使用 `mapActions` 辅助函数来映射到组件 methods 中的 `this.$store.dispatch` 方法。 import { mapActions } from 'vuex'; export default { ...mapActions(['incrementIfOdd']), methods: { incrementIfOdd() { this.incrementIfOdd(); } }, }; });