Vuex
- 实现组件全局状态数据管理的一种机制,可以方便的实现组件之间数据的共享
- 能够在vuex中集中管理共享数据,易于开发和后期维护
- 能够高效的实现组件之间的数据共享,提升开发效率
- 存储在vuex中的数据是响应式的,能够实时保持数据与页面同步
- 只有共享的数据才有必要存储到vuex中,对于组件私有的数据,存储到自身data中
- 基本使用
npm i vuex -S
import Vuex from 'vuex'
Vue.use(Vuex)
const store=new Vuex.Store({
// state里存放的就是全局共享的数据
state:{count:0}
})
new Vue({
store
})
- vuex的核心概念
- state-提供唯一的公共数据源,所有共享的数据都要统一放到store的state中进行存储
//1.获取数据方法一,直接调用
this.$store.state.全局数据名称
//2.获取数据方法二,mapState函数,映射为当前组件的计算属性
import {mapState } from 'vuex'
computed:{
...mapState(['count'])
}
- Mutation - 用于变更Store中的数据-只能用它变更Store数据,不可以直接操作,虽然繁琐,但可以集中监控所有数据的变化,!!!不可以执行异步操作
//1.定义Mutations
mutations:{
add(state,step){
// 变更状态
state.count+=step
}
}
// 2. 触发mutation
//触发mutations的第一种方式
methods:{
handle1(){
this.$store.commit('add',3)
}
}
//触发mutations的第二种方式
import {mapMutations} from 'vuex'
methods:{
...mapMutations(['add']),
handler(){
this.sub(3)
}
}
- Action-用于处理异步任务,如果通过异步操作变更数据,必须通过Action,但实质是通过触发Mutation的方式间接变更数据
// 定义action
actions:{
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step)
},1000)
}
}
//触发action第一种方式
methods:{
handle(){
this.$store.dispatch('addAsync',5)
}
}
// 触发action的第二种方式
import { mapActions} from 'vuex'
methods:{
...mapActions(['addAsync']),
handler(){
this.addAsync(5)
}
- Getter -对store中的数据进行加工处理形成新的数据,不会修改,只会包装state数据
// 定义getter
getters:{
showNum:state=>{
return '最新的数量是【'+state.count+'】'
}
}
// 使用getter的第一张方法
this.$store.getters.名称
// 使用getter的第二种方法
import{ mapGetters }from 'vuex'
computed:{
...mapGetters(['showNum'])
}