1.vuex是什么
是实现组件全局状态(数据)管理的一种机制,可以方便实现组件之间数据的共享。
2.使用vuex统一管理状态的好处
(1)能够在vuex中集中管理共享数据,易于开发和后期维护
(2)能够高效实现组件之间的数据共享,提高开发小率
(3) 存储在vuex数据都是响应式的,能够保存数据与页面的同步
3. 步骤
(1)安装vuex包
npm i vuex --save
(2)导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
(3)创建store对象
const store = new Vuex.store({
state:{count:0}
})
(4)讲store对象挂载到vue实例中
new Vue({
el:'#app',
render:h=>h(app),
router,
store
})
4.使用State
(1)组件访问State中第一种方式
this.$stort.state.全局数据名称
(2)组件访问State中第二种方式
1.按需导入
import {mapState} from 'vuex'
2.将全局数据,映射为当前组件的计算属性
computed:{
...mapState(['数据对象'])
}
5.使用mutation
第一种方法
用于变更Store的数据,但是不可以直接操作Store里面数据,mutation可以集中监控所有数据变化。
const store= new Vuex.Store({
state:{
变量:值
},
mutations:{
监控变量函数(state){
处理数据
}
}
)
触发mutation变量
method:{
处理事件函数(){
this.$store.commit(‘监控变量函数’)
}
第二种方法
映射方法
1、导入模块
import {mapMutations} from 'vuex'
2.映射当前组件函数
methods:{
...mapMutations(['监控变量函数'])
}
6.Action处理异步任务
第一种方法
this.$store.dispatch()
第二种方法
1.按需导入
import {mapActions} from 'vuex'
2.将全局数据,映射为当前组件的计算属性
computed:{
...mapActions(['数据对象'])
}
3.在methods里面使用
数据对象()
7.getters计算属性
1.方法一:
this.$store.getters.名字
2.方法二:
1.按需导入
import {mapGetters} from 'vuex'
2.将全局数据,映射为当前组件的计算属性
computed:{
...mapGetters(['数据对象'])
}