vuex getter and actions

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写一个消消乐游戏

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • --01-- 我是一只新鬼,因为一场大病死的,倒也没什么痛苦,死的时候有个声音告诉我这是我的命。 我晃晃悠悠从身体...
    liampomn阅读 527评论 14 4
  • 八月十八潮,壮观天下无! 2017年 10月7日 星期六 晴 说实话,一直以来孤陋寡闻的我,对于农...
    追梦CEO阅读 544评论 25 14
  • 形容孤独的姑娘是孤独的孤, 形容孤独的姑娘是孤独的独。 有句话说,在爱情中,我是爱你的,你是自由的。 其实友情亦然...
    下雪也温暖M阅读 324评论 0 1
  • 当鸟儿在枝头不在是为了唱歌 当蜜蜂在花丛中不在是为了采蜜 当世界上看似单纯的事 变得不像表面那样简单 当所有人都戴...
    蔓草精阅读 231评论 3 2
  • *解析 模块是可以实现特定功能的一组代码。 由于JS不能handle超大规模代码,所以要借鉴其它语言处理这种问题的...
    jrg_memo阅读 249评论 0 0