Vuex教程

发布时间 2023-06-25 17:16:53作者: MARSHBAN

Vuex使用场景:全局管理数据

注意:vue2项目要安装vuex3版本,vue3项目要安装vuex4版本

安装

npm install vuex@3 --save

建立以下目录结构

/ src
	/ store
		- store.js

创建vuex store

vuex 中最关键的是store对象,这是vuex的核心。可以说,vuex这个插件其实就是一个store对象,每个vue应用有且仅有一个store对象。

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    // 在这里定义你的状态
    count: 0,
    username: 'zhangsan'
  },
  mutations: {
    // 在这里定义你的mutations
    increment(state) {
      state.count++;
    },
    setUsername(state, username) {
      state.username = username;
    }
  },
  actions: {
    // 在这里定义你的actions
    asyncFetchUsername({ commit }) {
      // 模拟异步请求数据
      setTimeout(() => {
        const username = 'John Doe';
        commit('setUsername', username);
      }, 1000);
    }
  },
  getters: {
    // 在这里定义你的getters
    getCount(state) {
      return state.count;
    },
    getUsername(state) {
      return state.username;
    }
  }
});

export default store;

引入store

//main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';

new Vue({
  store,
  render: h => h(App)
}).$mount('#app');

在组件中使用Vuex

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Username: {{ username }}</p>
    <button @click="increment">Increment</button>
    <button @click="fetchUsername">Fetch Username</button>
  </div>
</template>

<script>
export default {
  computed: {
    count() {
      return this.$store.getters.getCount;
    },
    username() {
      return this.$store.getters.getUsername;
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment');
    },
    fetchUsername() {
      this.$store.dispatch('asyncFetchUsername');
    }
  }
}
</script>

总结

getters和mutations是Vuex中的两个核心概念,它们在用途和作用上有一些区别。

  1. Getters(获取器)
    ○ Getters用于从state中派生出新的数据,类似于计算属性。它们可以对state进行处理和计算,并返回一个新的值。
    ○ Getters可以被视为Vuex Store的计算属性,它们的返回值会被缓存,只有当依赖的state发生改变时才会重新计算。
    ○ Getters通过在Store中定义getters对象来声明。
    ○ 在组件中可以通过this.$store.getters来访问和使用Getter的返回值。
  2. Mutations(变更)
    ○ Mutations是用于修改state的方法。它们是唯一可以修改state的方式。
    ○ Mutations必须是同步函数,用于确保状态的变更是可追踪和可预测的。
    ○ Mutations通过在Store中定义mutations对象来声明。
    ○ 在组件中可以通过this.$store.commit来触发Mutation的执行,从而修改state中的数据。
    总结:
    ● Getters用于派生状态,对state进行计算和处理,并返回新的值,类似于计算属性。
    ● Mutations用于修改state,是唯一可以直接修改state的方式,但要确保是同步的。