怎么使用vuex map形式
使用Vuex的map形式可以方便地将Vuex中的状态映射到组件的计算属性或者方法中。
首先,在组件中引入Vuex,并使用mapState、mapGetters、mapMutations或者mapActions来创建映射关系。
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
然后,在computed中使用mapState或者mapGetters来映射Vuex中的状态或者计算属性。
computed: {
...mapState(['count']),
...mapGetters(['doubleCount'])
}
在上面的例子中,count是Vuex中的状态,而doubleCount是一个计算属性。
接下来,在methods中使用mapMutations或者mapActions来映射Vuex中的mutations或者actions。
methods: {
...mapMutations(['increment']),
...mapActions(['asyncIncrement'])
}
在上面的例子中,increment是一个mutation,asyncIncrement是一个action。
最后,在模板中可以直接使用映射的状态、计算属性、mutations或者actions。
<div>{{ count }}</div>
<div>{{ doubleCount }}</div>
<button @click="increment">Increment</button>
<button @click="asyncIncrement">Async Increment</button>
这样就可以通过映射的方式使用Vuex中的状态、计算属性、mutations或者actions了。
原文地址: http://www.cveoy.top/t/topic/i7qT 著作权归作者所有。请勿转载和采集!