这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战
State
State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储
const store = new Vuex.Store({
// state中存放的就是全局共享的数据
state:{count:0}
})
- 组件访问State中数据的第一种方式
{{this.$store.state.全局数据名称}}
- 组件访问State中数据的第二种方式
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:
computed:{
...mapState(['count'])
}
{{全局数据名称}}
Mutation
用于变更Store中的数据
使用Mutation可以集中监控所有数据的变化
const store = new Vuex.Store({
state:{
count:0
},
mytations:{
add(state){
// 变更状态
state.count++
},
addN(state, step) {
state.count += step
}
}
})
- 触发mutation的第一种方式
methods:{
handle1(){
this.$store.commit('add')
},
handle2(){
this.$store.commit('addN',3)
}
}
"3"就是step , commit的作用,就是调用某个mutation函数
- 触发mutation的第二种方式
import {mapMutations} from 'vuex'
通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:
methods:{
...mapMutations(['add','addN']),
btnHander1() {
this.sub()
},
btnHander2() {
this.subN(3)
},
}
Action
Action用于处理异步任务
const store = new Vuex.Store({
mutations:{
add(state){
state.count++
},
addN(state,step){
state.count += step
}
},
actions:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
},
addAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
})
- 第一种触发Action的方式
methods:{
handle(){
this.$store.dispatch('addAsync')
},
handle(){
this.$store.dispatch('addAsync',5)
}
}
- 第二种触发Action的方式
import {mapActions} from 'vuex'
methods:{
...mapActions(['addAsync','addNAsync'])
}
Getter
Getter用于对store中的数据进行加工处理形成新的数据
- Getter负责加工已有数据产生新数据,并不会修改原有数据
- 当原有数据变化时,Getter也会随之变化
const store = new Vuex.store({
state:{
count:0
},
getters:{
showNum:state=>{
return '当前最新的数量是['+state.count+']'
}
}
})
- 使用getters的第一种方式
this.$store.getters.名称
- 使用getters的第二种方式
import {mapGetters} from 'vuex'
computed:{
...mapGetters(['showNum'])
}
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接受 state 作为其第一个参数:
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
通过方法访问
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})