vuex中…mapMutations的使用
首先在vue2中mutations的使用方法是:
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
counter: 1000
},
mutations: {
// 方法
increment() {
this.state.counter++
},
decrement() {
this.state.counter--
}
}
})
然后在组件里写方法提交
methods: {
addition() {
this.$store.commit('increment')
},
subtraction() {
this.$store.commit('decrement')
}
},
最后就可以在组件里使用:
<button @click="addition">+</button>
<button @click="subtraction">-</button>
然而vue3中的mapMutations简化了这样的写法
mutations: {
// 方法
increment() {
this.state.counter++
},
decrement() {
this.state.counter--
}
}
在组件中
import {mapMutations} from 'vuex'
methods: {
...mapMutations(['increment','decrement'])
}
然后就可以直接在组件里使用:
<button @click="increment">+</button>
<button @click="decrement">-</button>
同理,对于…mapState
vue2中的使用方法是:
const store = new Vuex.Store({
state: {
counter: 1000
}
}
然后在组件中:
<h2>{{$store.state.counter}}</h2>
vue3中的…mapState:
import {mapState} from 'vuex'
computed:{
...mapState(['counter'])
}
就可以直接在组件里使用:
<h2>{{counter}}</h2>
当然还有很多别的写法…只写点最常用的吧
本文介绍了Vuex在Vue2到Vue3中mapMutations和mapState的使用方式变化。在Vue2中,需要手动在组件中调用$store.commit来提交mutation,而在Vue3中,通过引入mapMutations辅助函数,可以直接将mutation方法映射到组件的方法中。同样,对于state的获取,Vue2中直接使用$store.state,Vue3则可以借助mapState将state属性映射到计算属性。这些改变简化了Vuex在Vue3中的集成和使用。

1671

被折叠的 条评论
为什么被折叠?



