Vuex
Vuex是实现组件全局状态(数据)管理的一种机制, 可以方便的实现组件之间的数据共享。
Vuex 的基本使用
1.安装依赖包
npm install vuex -S
2.导入包
import Vuex from 'vuex'
3.创建 store 对象
const store = new Vuex.Store({
state:{count:0}
})
4.将 store 对象挂载到 vue 实例中
new Vue({
el:'#app',
render:h=>h(app),
router,
store
})
Vuex 的核心概念
组件访问 State 中数据的方式
-
this.$store.state.全局数据名称
-
从 vuex 中按需导入 mapState 函数
import { mapState } from 'vuex'
通过刚才导入的mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性
computed:{ ...mapState(['count']) }
Mutation
Mutation 用于变更 Store 中的数据
-
只能通过mutation变更 Store 数据,不可以直接操作 Store 中的数据
-
通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
-
不要在 mutation 函数中 , 执行异步操作
-
const store = new Vuex.Store({
state:{
count:0
},
mutations:{
add(state){
//变更状态
state.count++
//如果传入其他参数
add(state,step){
state.count+=step
}
}
}
})
// 触发mutation
methods:{
headle1(){
this.$store.commit('add')
}
}
//如果传入多个参数
this.$store.commit('add',3)
Action
Action用于处理异步任务
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation ,但是在Action 中还是要通过触发Mutation的方式间接变更数据。
// 定义Action
const store = new Vuex.store({
...
mutation :{
add(state){
state.count++
}
},
Action:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
})
// 触发Action
methosd:{
headle(){
// 触发Action的第一种方式
this.$store.dispatch('addAsync')
}
}
传入多个参数,同Mutation
Getter
Getter 用于对Store 中的数据进行加工树立形成新的数据。
1.Getter 可以对 Store 中已有的数据加工处理后形成新的数据,类似Vue的计算属性
2.Store中数据发生变化,Getter 的数据也会跟着变化。
// 定义 Gettter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state=>{
return '当前最新的数量是【'+state,count+'】'
}
}
})
使用getters的第一种方式
this.$store.getters.名称
使用getters的第二种方式
import { mapGetters } from 'Vuex'
comoputed:{
...mapGetters(['showNum'])
}