全局数据共享vuex的一些总结 | 青训营笔记

64 阅读2分钟

这是我参与【第四届青训营】笔记创作活动的第2天

vuex是什么

上一篇笔记总结了组件通信常见的方式,最后也简单提了vuex在组件通信中的作用。这次就来细谈一下vuex的使用

vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。基本原理如图

image.png

vuex的基本使用

  1. 安装vuex依赖包
npm i vuex --save
  1. 导入vuex包
import Vuex from 'vuex'

3.创建store对象

const store = new Vuex.Store({
	state: {}
	getters: {}
	mutations: {},
	actions: {},
	modules: {}
})

export default store

4.将store对象挂载到vue实例中

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

其中,第3步的store对象可以单独放在一个store.js的文件中,并向外暴露store对象,然后在main.js入口文件中接收并挂载到vue实例上

vuex的核心概念

  • state
  • mutations
  • actions
  • modules

state

state提供唯一的公共数据源,所有共享的数据都要统一放到Store的state中进行存储

// 创建store的数据源,提供唯一公共数据
const store = new Vuex.Store({
    state:{
        count:0
    }
})

在组件中使用store里的数据方式一:

this.$store.state.count

在组件中使用store里的数据方式二:

// 1.按需导入mapState辅助函数
// 2.映射为当前组件的computed计算属性
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState(["count"]),
  },
};

mutations

mutation用于变更store中存储的数据 值得注意的是:

  1. 只能通过mutation变更store中的数据,不可以在组件中直接更改store中的数据
  2. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化

在mutations节点中的每个函数,第一个形参state可以访问store里state里的数据,第二个参数用于接收参数,称为载荷

const store = new Vuex.Store({
    mutations:{
	add(state) {
            state.count++
	},
    }
})

在组件中更改store里的数据方式一:

this.$store.commit("add");

在组件中更改store里的数据方式二:

// 1.按需导入mapMutations辅助函数
// 2.映射为当前组件的methods中的方法
import { mapState } from "vuex";
export default {
  methods: {
    ...mapMutations(["add"]),
  },
};

actions

actions节点用于存储异步处理的函数 在actions节点中的每个函数,形参context可以访问store里mutations里的方法

const store = new Vuex.Store({
    actions:{
	addAsync(context) {
		setTimeout(() => {
			context.commit('add');
		}, 1000);
	},
    }
})

在组件中使用actions的方法方式一:

this.$store.dispatch('addAsync')

在组件中使用actions的方法方式二:

// 1.按需导入mapActions辅助函数
// 2.映射为当前组件的methods中的方法
import { mapState } from "vuex";
export default {
  methods: {
    ...mapActions(["addAsync"]),
  },
};

getters

getter用于对store中的数据进行加工处理形成新的数据

  1. getter可以对store中已有的数据加工处理后形参新的数据,类似于Vue的计算属性
  2. store中的数据发生变化,getter的数据也会跟着变化
  3. 不能在getter中修改state的值
const store = new Vuex.Store({
    getters:{
	getNum(state) {
		return state.count
	}
    }
})

在组件中使用getters方式一:

this.$store.getters.getNum

在组件中使用getters方式二:

// 1.按需导入mapGetters辅助函数
// 2.映射为当前组件的computed计算属性
import { mapState } from "vuex";
export default {
  computed: {
    ...mapGetters(["getNum"]),
  },
};