1辅助函数(又称语法糖)
分为四个
- mapState
- mapMutations
- mapGetters
- mapActions
2.当一个组件需要多个状态的时候,这些状态都声明成计算属性过于偏长于是就有了辅助函数
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'
computed:{
...mapState({
a:"a", // "a" 指的是state中的a
b:"b"
}),
...mapGetters({
Val:'newVal' // 可以重新命名
})
}
methods:{
...mapActions({
getSync:'getSyncNum'
})
...mapMutations({
increament:"increament"
})
}
template
{{a}} {{b}}
{{getSync(1)}}
<button @click='increament(1)'></button>
3.在vue页面中引入辅助函数
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
4.辅助函数注意事项
1.注意事项:
mapState与mapGetters推荐在计算属性里使用,可以直接做data数据使用
2. computed: {
...mapState(["shopData"]),
},
3.其他辅助函数在methods里
methods: {
...mapActions(["getData"]),
...mapMutations(["add"]),
}
5.model模块化管理数据
- 状态树结构复杂的时候,可以用modules进行管理
- 多人协作开发,可以用modules,避免命名空间冲突
//创建store,分模块定义
const test1 ={
namespaced:true, //开启命名空间,在各组件总 ...mapState("test1",{name:"name"})
state:{name:'test1'},
actions:{},
mutations:{
changeName(state,arg){
state.name=arg;
},
getters:{}
}
const test2 = {
namespaced:true,
state:{},
actions:{},
mutations:{
}
},
getters:{}
}
new Vuex.Store({
state:{name:"root"},
actions,
mutations,
getters
modules:{
test1,
test2
}
})
在组件中使用:
{{this.$store.state.name}}
{{name}}
{{this.$store.state.test1.name}}
{{tes1Name}}
computed:{
...mapState({
name:“name"
}),
...mapState('test',{
test1Name:'name'
})
}
methods:{
...mapMutations('test1',['changeName'])
}
5.vuex超级篇,数据持久化
1.什么是数据持久化
刷新页面,数据丢失,清空,有时候我们需要把一些数据固话到本地,即使刷新也不能清空,例如:登录状态,token等
这是就需要到vuex数据持久化
2.安装
npm install vuex-persistedstate --save