vuex
Action
//action类似于mutation,不同在于
//▇1.action提交的是mutation,而不是直接变更状态
//2.action可以包含任意异步操作
const store =createStore({
state:{
count:0
},
mutations:{
increment(state){
state.count++
}
},
actions:{
increment(context){
context.commit('increment')
}
// 参数解构 increment({commit}){
//commit('increment')
//}
}
})
actions:{
incrementAsync({commit}){
setTimeout(()=>{
commit('increment')
})
}
}
//载荷
this.$store.dispatch('incrementAsync',10)
//▇如果在不同的module文件找那个
this.$store.dispatch('user/incrementAsync',10)
//对象
store.dispatch({
type:'incrementAsync',
amount:10
})
//...mapActions辅助函数
methods:{
...mapActions(['increment','incrementAsync'])
...mapActions({
add:'increment'
})
}
//如果有参数
<div @click="increment(100)">加加{{ $store.state.user.count }}</div>
Mutation
//▇更改vuex的store中的状态唯一方法是提交mutation
const store={
state:{
count:1
},
mutations:{
increment(state){
state.count++
}
}
}
//提交载荷payload,你可以向store.commit传入额外的参数,即mutation的载荷payload
mutations:{
increment(state,n){
state.count+=n
}
}
store.commit('increment',10)
//载荷应该是一个对象
mutations:{
increment( state,payload){
state.count+=payload.amount
}
}
store.commit('increment',{ amount:10 })
import { mapMutations } from 'vuex'
methods:{
...mapMutations([
'increment',
'incrementBy'
]),
...mapMutations({
add:'increment'
})
addNum(){
this.$store.commit('user/ADD_NUM',10)
}
}
Getter
//有时候我们需要从store中的state中派生出一些状态
const store =createStore({
state:{
todos:[
{ id:1, text:'...',done:true},
{ id:2, text:'...',done:false}
]
}
getters:{
doneTodos:(state)=>{
return state.todos.filter(todo => todo.done)
}
}
})
import { mapGetters } from 'vuex'
computed:{
...mapGetters([
'done',
'add'
]),
doneTodos(){
return this.$store.getters.doneTodos
}
}
state
import { mapState } from 'vuex'
computed: mapState({
name: (state) => state.user.name,
avatar: (state) => state.user.avatar,
num: (state) => state.user.num,
}),
vuex能够记录每一次state的变化记录,保存状态快照,实现时间漫游/回滚之类的操作。