VUEX 的使用以及其模块化

本文介绍了Vuex,一个Vue.js应用的状态管理模式,详细阐述了state、mutations、actions和getters的作用。讲解了如何安装、使用Vuex,以及模块化和命名空间的实践,以及在组件中通过辅助函数访问状态和执行操作的方法。
摘要由CSDN通过智能技术生成

简介

Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态的一致性。

核心

Vuex的核心包括state、mutations、actions和getters。

  1. state: Vuex中的状态存储。可以将它看作是应用程序的单一数据源,类似于Vue实例的data对象。

  2. mutations: Vuex中的状态修改。mutations是唯一允许修改state的地方,每个mutation都有一个字符串类型的事件类型和一个回调函数,用于对state进行修改。

  3. actions: Vuex中的异步操作。actions可以包含任意异步操作,通过提交mutation来间接修改state。

  4. getters: Vuex中的派生状态。getters可以通过对state的计算和处理返回一个新的状态,类似于Vue的计算属性。

安装

安装Vuex:可以通过npm、yarn或者CDN等方式安装Vuex。

npm i vuex --save
yarn add vuex

使用

在src目录下创建store文件夹:在store下新建index.js后续引入到main.js内。

注:vuex推荐使用模块化方式,尽量避免全部放在index.js内,存在命名问题,模块化的文件需添加 namespaced: true 开启命名空间。

命名空间:Vuex 的命名空间是一种将模块化的状态和操作方法进行隔离的机制。通过使用命名空间,可以在多个模块中定义相同的 state、getters、mutations、actions 等,而不会发生命名冲突。同时,在组件中调用模块中的状态和操作方法时,也需要加上命名空间前缀。

import Vue from "vue";
import Vuex from "vuex";
import user from "./modules/user";
import getters from "./getters";
Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user,
  },
  getters,
});

export default store;

全局挂载

import Vue from "vue";
import App from "./App.vue";
import store from "./store";

Vue.config.productionTip = false;
Vue.prototype.$store = store;
new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");

组件内使用 (常规方式)

// 组件中使用
export default {
  computed: {
    count() {
      return this.$store.state.dataNmae
    },
    doubleCount() {
      return this.$store.getters.dataNmae
    }
  },
  methods: {
    increment() {
      this.$store.commit('mutations')
    },
    incrementAsync() {
      this.$store.dispatch('actions')
    }
  }
}
 

组件内使用(辅助函数方式)

在组件中访问命名空间模块的状态和操作方法时,需要使用 mapStatemapGettersmapMutationsmapActions 等辅助函数时,也需要指定命名空间前缀。


import { mapGetters, createNamespacedHelpers } from "vuex";
const { mapMutations, mapState, mapActions } = createNamespacedHelpers("user");
export default {
  components: {},
  data() {
    return {};
  },
  computed: {
    ...mapGetters(["name"]),
    ...mapState({
      stateName: (state) => state.name,
    }),
  },
  created() {},
  methods: {
    ...mapActions(["Actions"]),
    ...mapMutations(["Mutations"]),
    handleChangeName() {
      this.$store.commit("user/Mutations", "data");
    },
    handleChangeNameHelp() {
      this.Mutations("data");
    },
    handleChangeNameAsyc() {
      this.$store.dispatch("user/Actions", "data");
    },
    handleChangeNameHelpAsyc() {
      this.Actions("data");
    },
  },

辅助函数与原型在dom上使用的区别

 <div>原型写法:{{ $store.state.user.name }}</div>
 <div>mapStates写法:{{ stateName }}</div>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值