Vuex学习总结 - State(3)
4.Vuex核心概念
4.1 State
使用mapState
。
import {mapState} from 'vuex'
export default {
name: "Counter",
// computed: {
// count() {
// return this.$store.state.count
// }
// },
computed: mapState({
count: state => state.count
}),
methods: {
increment() {
this.$store.commit('increment')
}
}
}
<template>
<div>
<button @click="increment">加一</button> {{count2}}
<br/>
{{countAlias1}}
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
name: "Counter",
// computed: {
// count() {
// return this.$store.state.count
// }
// },
computed: mapState({
count2: state => state.count,
countAlias1: 'count2'
}),
methods: {
increment() {
this.$store.commit('increment')
}
}
}
</script>
<template>
<div>
<button @click="increment">加一</button> {{count}}
<br/>
{{countAlias}}
<br/>
{{countPlusLocalState}}
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
name: "Counter",
data() {
return {
localCount: 2
}
},
computed: mapState({
count: state => state.count,
countAlias: 'count',
countPlusLocalState(state) {
return state.count + this.localCount
},
}),
methods: {
increment() {
this.$store.commit('increment')
}
}
}
</script>
将本地计算属性与mapState
合并的方法。
<template>
<div>
<button @click="increment">加一</button> {{count}}
<br/>
{{localComputed}}
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
name: "Counter",
data() {
return {
localCount: 2
}
},
computed: {
localComputed () {
return this.count + this.localCount
},
...mapState(['count']),
},
methods: {
increment() {
this.$store.commit('increment')
}
}
}
</script>
Vuex实例中的共享状态可以被追踪和调试,如果一个状态属于单个组件,那么将其保留为本地状态就可以了。