Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理数据。简言之就是用来集中管理组件中共享数据的一种状态管理模式。
安装
npm i vuex -S
配置
先在 vue项目的src目录下创建一个store文件,在store文件夹下在创建index.js文件
在index.js中进行配置
import Vue from 'vue'
import Vuex from 'vuex'
//将 $store 挂载到vue组件
vue.use(Vuex)
// option指具体的配置项
const store = new Vuex.Store(option)
export default store
option选项
state
state中存放所有共享的数据
index.js
option = {
state : {
name:'张三',
age: 19
}
}
在其他组件中使用state中的数据
方法一:
this.$store.state.name
方法二:
import { mapState } from 'vuex'
export default{
computed: {
...mapState(['name']),
}
}
mutation
在mutation中操作所有同步数据
index.js
option = {
mutation: {
//第一个参数表示 store.state,第二个参数是传入的值,如果不传参,则默认参数为李四
setname(state,val='李四'){
state.name = val
},
addAge(state,val=1) {
state.age += val
}
}
}
在其他组件中使用
方法一:
this.$store.commit('mutation中的一个函数名',该函数的参数)
方法二:
import { mapMutation } from 'vuex'
export default {
methods: {
...mapMutation('setname')
},
created(){
//调用setname
this.setname('王五')
}
}
actions
对异步数据进行修改,但不是直接修改,而是通过mutation间接修改
index.js
option = {
actions: {
asycnAddAge(store,val) {
setTimeOut(()=>{
//让年龄每隔1秒,加2
store.commit('addAge',2)
},1000)
}
}
}
其他组件使用
方法一:
this.$store.dispatch('asycnAddAge', 具体值)
方法二:
import { mapActions } from 'vuex'
export default {
methods: {
// 2. 把actions里方法映射到原地
...mapActions(['asyncAddAge'])
}
}
getters
就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
index.js
option = {
state: {
age: 13
},
getters: {
addAge : (state) => {
return state.age+1
}
}
其他组件使用
方法一:
this.$store.getters.addAge // 14
方法二:
import { mapGetters } from 'vuex'
export default {
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters(['addAge'])
}
}