29.Getter and Mutation

Vuex内的getter,相当於component内的computed,作用都是改变资料的表示形式

Getter:
就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getter 接受 state 作为其第一个参数:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
    },
    getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
    }
  }
})
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
store.getters.doneTodosCount // -> 1
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

component中使用:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

mapGetters 辅助函数:
将 store 中的 getter 映射到局部computed属性

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'anotherGetter',
      // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
      doneCount: 'doneTodosCount'
      // ...
    ])
  }
}

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。

Mutation:
每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler),并且它会接受 state 作为第一个参数:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

需要以相应的 type 调用 store.commit 方法:

store.commit('increment')

可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

或直接使用包含 type 属性的对象

store.commit({
  type: 'increment',
  amount: 10
})

Mutation 必须是同步函数,函数内部只可执行同步事件;若函数内部执行非同步事件的话会导致函数永远无法完成

component内使用mutation:

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

<<:  Day [29] Azure Custom Vision-Line Chatbot整合(一)

>>:  Day29 | 使用extension动态产生snippet提示吧!

[D03] 取样与量化(1)

我们在用电脑处理影像时,由於电脑只看得懂数字,所以影像必须要以离散(discrete)的形式处理,也...

Day#10 Struct

来到了第十天,今天要更深入了解 struct 在 Go 里面扮演的角色, 话不多说,我们就进入正题吧...

来做一个色码转换器吧!

前言 今天来做一个色码转换器~ 我们先认识色码之间的关系,拆解步骤後再一步步完成吧! 颜色表示的方法...

为何要执行弱点评估

前几天我们说明了社交工程认知的一些基础 相较之下没提到什麽技术或工具 接下来将进入弱点评估和扫描.....

【LeetCode】DFS

今天出去玩,买了好多东西,只想赶快把这篇赶出来。 DFS:碰到一个新节点时,先从这个新节点开始往下做...