vuex 中的 getters
文档对于component 中 vuex 属性块的描述其中包括了对 getter 的描述(黑体标粗).
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函数必须是纯净的.
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.
对应代码
// 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>
//没有传任何值,而且没有调用,就可直接用呀
</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 函数
未完待续vue学习中,今天刚看了一下vuex弥补一下没有学习flux的遗憾,准备利用
vue,vuex,node.js重构一下微博应用,如果时间充裕再用vue写一个消消乐游戏