1、什么是Vuex?
Vuex是专门为Vue.js设计的状态管理库,采用集中方式管理应用的所有组件状态,并以相应的规则保证状态以一种可预测的方式变化。简而言之,就是采用全局模式,将组件的共享状态抽离出来管理,使组件树中每一个位置都可以获取共享的状态或触发行为。
Vuex的核心概念有State, Getter, Mutation, Action, Module。下面简要介绍:
State定义共享状态,即变量;
Getter是基于state的派生状态,可理解为组件中的计算属性;
Mutation是更改状态的唯一方法,通过提交mutation修改状态,同步操作;
Action类似mutation,通过mutation修改状态,支持异步操作;
Module就是模块,在大型项目中为方便状态管理和协作开发,将store拆分为多个子模块,每个模块拥有完整的state, mutation, action, getter。
2、Vuex安装
npm install vuex --save
3、Vuex使用
(1)、创建vuex文件夹,并创建store.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
})
(2)、在根实例中注册store(main.js)
import store from './vuex/store'
new Vue({
...
store,
...
})
3、store中变量的定义、管理、派生
(1)、state(状态)
在store.js中
const state = {
name: '小明'
}
export default new Vuex.Store({
state
})
在应用程序中
<template>
<div>store中的姓名:{{this.$store.state.name}}</div>
</template>
<script>
export default {
mounted () {
console.log(this.$store)
}
}
</script>
(2)、mutation(更改store状态的唯一方法)
在store.js中
const mutations = {
setName (state) {
state.name = '小明'
}
setNameWithParam (state, param) {
state.name = param.name
}
}
export default new Vuex.Store({
mutations
})
在应用程序中
<script>
export default {
methods: {
setNameDefault () {
this.$store.commit('setName')
},
setNameByParam () {
this.$store.commit({
type: 'setNameWithParam',
name: this.name
})
}
}
}
</script>
(3)、action(异步更改状态)
在store.js中
const actions = {
setNameAsync (context) {
let _name = context.state.name
setTimeout(()=>{
context.commit('setName')
}, 1000)
}
setNameWithParamAsync (context, param) {
setTimeout(()=>{
context.commit('setNameWithParam', param)
}, 1000)
}
}
export default new Vuex.Store({
actions
})
在应用程序中
<script>
export default {
methods: {
setNameDefaultAsync () {
this.$store.dispatch('setNameAsync')
},
setNameAsync () {
this.$store.dispatch({
type: 'setNameWithParamAsync',
name: this.name
})
}
}
}
</script>
(4)、getter(state的派生状态)
getter可以将对store中某个属性相同的处理操作抽出来,做一个公共的处理。
const getter = {
formatName: state => {
let postfix = ''
if(state.name === '小明'){
postfix = '很好'
}
return state.name + postfix
},
customerFormatName: (state)=>(val)=>{
let postfix = ''
if(state.name === '小明'){
postfix = val
}
return state.name + postfix
}
}
export default new Vuex.Store({
getters
})
在应用程序中
<div>
<b>{{this.$store.getter.formatName}}</b>
<b>{{this.$store.getter.customerFormatName('非常好')}}</b>
</div>