vuex 中的 getters
文檔對于component 中 vuex 屬性塊的描述其中包括了對 getter 的描述(黑體標(biāo)粗).
Note the special vuex option block. This is where we specify what state the component will be using from the store. For each property name, we specify a getter function which receives the entire state tree as the only argument, and then selects and returns a part of the state, or a computed value derived from the state. The returned result will be set on the component using the property name, just like a computed property.
getters函數(shù)必須是純凈的.
All Vuex getters must be pure functions - they take the entire state tree in, and return some value solely based on that state. This makes them more testable, composable and efficient. It also means you cannot rely on this inside getters.
對應(yīng)代碼
// vuex/store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
count: 0
}
const mutations = {
INCREMENT (state) {
state.count++
}
}
export default new Vuex.Store({
state,
mutations
})
// templages/Display.vue
<template>
<div>
<h3>Count is {{ counterValue }}</h3>
//沒有傳任何值涉馅,而且沒有調(diào)用贮懈,就可直接用呀
</div>
</template>
<script>
import { getCount } from '../vuex/getters'
export default {
vuex: {
getters: {
counterValue: getCount
}
}
}
</script>
//vuex/getter.js
export function getCount (state){
return state.count;
}
Actions
Actions are just functions that dispatch mutations. By convention, Vuex actions always expect a store instance as its first argument, followed by optional additional arguments:
// vuex/action.js
export const incrementCounter = function ({ dispatch, state }) {
dispatch('INCREMENT', 1)
}
// components/Increment.vue
<template>
<div>
<button @click='increment'> Increment +1 </button>
</div>
</template>
<script>
import { incrementCounter } from '../vuex/action'
export default {
vuex: {
actions: {
increment: incrementCounter
}
}
}
</script>
getter 和 actions 給我個人的感覺就像java 類中的 get 和 set 函數(shù)
未完待續(xù)vue學(xué)習(xí)中雁佳,今天剛看了一下vuex彌補一下沒有學(xué)習(xí)flux的遺憾见转,準(zhǔn)備利用
vue,vuex,node.js重構(gòu)一下微博應(yīng)用岖食,如果時間充裕再用vue寫一個消消樂游戲