一, Vuex状态管理介绍
本节内容:了解什么是状态管理;掌握Vuex的安装和配置;理解Vuex的原理;掌握查询Vuex中的数据
1,什么是Vuex
专门为Vue.js应用程序开发的状态管理模式:
state:驱动应用的数据源(data)
view:以声明方式将state映射到视图(template)
actions:响应在view上的用户输入导致的状态变化(method)
**对于一些小型项目,这样使用没问题,但如果是大型项目,同时有多个组件使用一个数据源会出现问题。Vuex是基于单例模式实现,一种全局的状态管理
state:存放数据;mutation:同步提交数据;action:异步提交数据
2, 安装及配置
- 第一步:安装 cnpm install vuex -S
- 第二步,配置
Vue.use(Vuex) export default new Vuex.Store({ state: {}, mutations:{}, actions:{}, modules:{} }) new Vue({ store })
state:单一状态树,全局唯一数据源
查询state中的数据:
computed: {
user() {
return this.$store.state.user
}
}
**总结:Vuex其实就是用来共享数据的
二,使用Vuex保存用户信息
本节内容:了解Vuex存储数据的原理;理解同步和异步的区别;如何进行数据的存储
1,mutation:更改store中状态的唯一方法(注意不要通过this.store直接进行赋值)
mutations: {
increment(state){
state.count++
}
}
store.commit('increment')
2, action:提交的是mutation,可异步
actions:{
increment(context){
context.commit('increment')
}
}
store.dispatch('increment')
Vuex相关代码优化
本节内容:了解Vuex提供的辅助函数;掌握mapState的使用;掌握mapMutation的使用;掌握mapActions的使用
1, mapState
import { mapState } from 'vuex'
computed: mapState({
username: state => state.user.username,
nickname: state => state.user.nickname
})
computed: mapState(['user', 'profile'])
computed: {
content() {
return ''
},
...mapState(['user', 'profile'])
}
2,mapMutations
import { mapMutations } from 'vuex'
methods: {
// ...mapMutations(['updateUsername']),
...mapMutations({
update: 'updateUsername'
}),
submit () {
// this.updateUsername({uname: this.uname})
this.update({uname: this.uname})
}
}
3,mapActions
import { mapActions } from 'vuex'
methods: {
// ...mapActions(['updateUser'])
...mapActions({
updateUserInfo: 'updateUser'
}),
submit() {
//this.updateUser({uname:this.uname})
this.updateUserInfo({uname:this.uname})
}
}