在中大型項目中,爲方便組件間通訊,因此有了vuex
Vuex 4個核心概念
- state 用來展示數據
- getter 用來美化數據
- mutation 用來計算數據
- actions 用來異步操作
如何使用
npm install vuex --save
在組件中
<template>
<div>
<h3>當前最新的count值爲:{{$store.state.count}}</h3>
<h3>{{$store.getters.showNum}}</h3>
<button @click="btnHandler2">+N</button>
<button @click="btnHandler4">+N Async</button>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
btnHandler2() {
// commit 調用 store.js 中mutation 函數
this.$store.commit('addN', 3)
},
btnHandler4() {
// dispatch調用 store.js 中actions 函數
this.$store.dispatch('addNAsync', 5)
}
}
}
</script>
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
// 只有 mutations 中定義的函數,纔有權利修改 state 中的數據
mutations: {
addN(state, step) {
state.count += step
},
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}
},
//異步專用
actions: {
addNAsync(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
},
subAsync(context) {
setTimeout(() => {
context.commit('sub')
}, 1000)
},
subNAsync(context, step) {
setTimeout(() => {
context.commit('subN', step)
}, 1000)
}
},
getters: {
showNum(state) {
return '當前最新的數量是【' + state.count + '】'
}
}
})
使用映射,簡化代碼
<template>
<div>
<!-- <h3>當前最新的count值爲:{{count}}</h3> -->
<h3>{{showNum}}</h3>
<button @click="btnHandler1">-1</button>
<button @click="subN(3)">-N</button>
<button @click="subAsync">-1 Async</button>
<button @click="subNAsync(5)">-N Async</button>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState(['count']),//映射 State 拿到count的值
...mapGetters(['showNum'])//映射 Getters 拿到showNum的值
},
methods: {
...mapMutations(['sub', 'subN']),// 映射到Mutations
...mapActions(['subAsync', 'subNAsync']), //映射到Actions
btnHandler1() {
this.sub()
}
}
}
</script>