Vuex在组件中使用或者重命名状态
Vuex 入门的文章都是照着文档来个最简单的例子而已,至于核心概念中的
在 Vuex 状态管理中,
一、最直接的使用方式
一般来说,最直接的使用方法就是直接在组件中将状态注入到每一个组件中
这样子就能够直接使用 $store.state.count
进行使用
- PS:(如果不知道为什么用 $store.state.count ,应该先看看文档 )
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
})
因此,如果需要 template 中不直接使用 {{$srore.state.count}}
的做法中可以这么使用:
data(){
return {
// 进行组件注入后,就可以直接使用 this.$store 调用 vuex 的状态实例
newCount:this.$store.state.count
}
}
二、使用 mapState 和 mapMutations 辅助函数
使用 mapState 和 mapMutations 的前提是要引入:
import store from '@/vuex/store';
import {mapState , mapMutations } from 'vuex'
一般来说我们都是避免直接使用 $store.state.count 或者是 $store.mutations.add
因此在组件中,methods 把状态变更的函数进行重命名:
// 这种方法是最简单的,但是缺点就是映射出来的 count() 方法 名称必须和 mutations 中的函数一样
// computed:mapState(['count']),
// 下面是集中不同的方式 一种是直接使用state,然后通过state的参数进行使用
// 在这个过程中,是可以使用this.num 来操作
computed:mapState({
count(state){
return state.count + this.num
},
countPlusLocalState(state){
return state.count + this.num
},
count2:'count'
}),
// 在使用mapmutations的时候,如果只是重命名,则直接下面的方式即可,即使需要传递参数
// 比如我在 store 中的 mutations里面定义的add函数是 add(state,num){return state.count + num}
// 我重命名之后 newAdd 在使用的时候 还是直接传参即可 <button @click="newAdd(10)"></button>
methods:mapMutations({
newAdd:'add',
newReduce:'reduce'
}),
三 完整示例
vuex/store.js
/**
* Created by Postbird on 2017/6/16.
*/
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state={
count:0,
}
const mutations={
add(state,n){
state.count+=n;
},
reduce:function (state) {
state.count--;
}
}
export default new Vuex.Store({
state,
mutations
})
组件
<template>
<div>
<h2>{{message}}</h2>
<hr>
<h3>【 {{count}} 】- 【 {{newCount}} 】 - 【 {{countPlusLocalState}} 】 - 【 {{count2}} 】</h3>
<p>
<button @click="newAdd(10)">+</button>
<button @click="newReduce">-</button>
</p>
</div>
</template>
<script>
import store from '@/vuex/store';
import {mapState , mapMutations } from 'vuex'
export default{
name:'Count',
store,
data(){
return {
message:'使用vuex计算Count',
newCount:this.$store.state.count,
num:1
}
},
// computed:mapState(['count']),
computed:mapState({
count(state){
return state.count + this.num
},
countPlusLocalState(state){
return state.count + this.num
},
count2:'count'
}),
methods:mapMutations({
newAdd:'add',
newReduce:'reduce'
}),
}
</script>
四、展开运算符
ES6里面的展开运算符能够更好的辅助去操作.
比如除了
// computed:mapState(['count']),
computed:{
...mapState({
count(state){
return state.count + this.num
},
countPlusLocalState(state){
return state.count + this.num
},
count2:'count',
}),
...mapGetters({
count3:'count',
}),
newMessage:function(){
return this.message.toUpperCase();
}
},
文章版权:Postbird-There I am , in the world more exciting!
本文链接:http://www.ptbird.cn/vuex-component-rename-state.html
转载请注明文章原始出处 !
扫描二维码,在手机阅读!