无标题文章

简介: 1. 映射为计算属性state: mapStates getters: mapGetters对 state 进行运算、过滤返回新的状态getters:接收 state 作为第一个参数,其它 getters 作为第二个参数getters: { // ... doneTodosCount: (state, getters) => { return getters.doneTodos.length }}让 getter 返回一个函数,来实现给 getter 传参。

1. 映射为计算属性

state: mapStates 
getters: mapGetters
对 state 进行运算、过滤返回新的状态

getters:接收 state 作为第一个参数,其它 getters 作为第二个参数

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

getters: {
  // ...
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

2. 映射为 mutation

你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

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')`
    })
  }
}

3. 执行 action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})
在组件中分发 Action

你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

import { mapActions } from 'vuex'

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

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}
目录
相关文章
|
前端开发
css 实现 title的效果,并且自己写修改类似title样式
css 实现 title的效果,并且自己写修改类似title样式
css 实现 title的效果,并且自己写修改类似title样式
|
12天前
|
存储 机器学习/深度学习 人工智能
【无标题】
【无标题】
|
算法 C++
无标题。。。
无标题。。。
|
Web App开发 移动开发 前端开发
HTML5关于contenteditable介绍
HTML5已经从一个新的名词变成了我们在项目中经常用到的东西了,今天我们就来分析一番其中contenteditable 。
149 0
|
应用服务中间件 nginx NoSQL
Title comes here
asdasdadawdwadaw
1440 0
无标题
   OOP是从静态角度考虑程序结构,OOP对业务处理过程中的实体、属性和行为进行抽象的封装以获得更加清晰高效化的逻辑划分。研究的是静态领域。 AOP从动态角度考虑程序运行过程,针对业务处理过程中的切面进行提取,所面对的是业务处理过程中的某个步骤或者阶段,研究的是一种动态的过程。
719 0