认识Vuex
vuex是什么
专门在Vue中实现集中式状态(数据)管理的一个vue插件,对vue应用中多个组件的共享状态进行集中式管理(读/写),也是一种组件间通信方式。且适用于任意组件间通信
Github地址
Vuex文档 https://github.com/vuejs/vuex
为什么使用vuex
多组件共享数据–全局事件总线实现
多组件共享数据–vuex实现
什么时候使用vuex
- 多个组件依赖同一状态
- 来自不同组件的行为需要变更为同一状态
vuex的工作原理图
vuex的使用
安装
-
安装vuex
npm i vuex
-
引入
import Vuex from 'vuex'
-
使用vuex
Vue.use(Vuex)
搭建vuex环境
store中的重要配置项
-
actions:
-
mutations:
-
state:
扫描二维码关注公众号,回复: 13421706 查看本文章 -
getters
:
1)创建文件 src/store/index.js
文件
// 该文件是准备vuex的核心 ==> store
// 引入Vue核心库
import Vue from "vue"
// 引入Vuex
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
// 准备actions对象 =>响应组件中用户的动作
const actions = {
}
// 准备mutations对象 =>修改state中的数据
const mutations = {
}
// 准备state对象 =>保存具体的数据
const state = {
}
// 准备getters对象 =>用于加工state中的数据
const getters = {
}
// 创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
2)在main.js
中创建vm
时传入store
配置项
// 引入vuex的核心 store
import store from './store/index.js'
// 创建vm
new Vue({
render:h=>h(App),
store
}).$mount('#app')
vuex的基本使用
-
组件中调用
dispatch
methods:{ increment(){ this.$store.dispatch('plus',this.number) } }
-
actions
中与之对应的函数,开始响应,调用commit()
,提交mutations
中 操作处理数据const actions = { plus(context,value){ console.log('actions中的plus调用了,响应组件中用户的动作') context.commit('PLUS',value) } }
const mutations = { PLUS(state,value){ console.log('mutations中的PLUS调用了,修改state中的数据') state.sum += value } }
组件中读取
vuex
中的数据:$store.state.sum
组件中修改vuex
中的数据:this.$store.dispatch('actions中的方法名',数据)
如果没有复杂逻辑,可以直接 this.$store.commit('mutations中的方法名',数据)
备注:若没有网络请求或其他业务逻辑,组件中也可以越过
actions
,即不写dispatch
,直接写commit
methods:{
increment(){
// this.$store.dispatch('plus',this.number)
// 没有业务逻辑,可以直接越过 actions,使用commit提交到 mutations中处理
this.$store.commit('PLUS',this.number)
}
}
vuex的配置项 getters
概念:当state
中的数据需要加工后再使用时,可以使用getters
加工
在store/index.js
中追加getters
配置
// 准备getters对象 =>用于加工state中的数据
const getters = {
bigSum(state){
return state.sum * 10
}
}
组件中读取数据:$store.getters.bigSum