无标题文章

简介: 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')`
    })
  }
}
目录
相关文章
|
30天前
|
前端开发 JavaScript
什么是HTML?
HTML是超文本标记语言,用于创建网页的标准语言,专注于内容结构和含义,不涉及样式。它由标签组成,如<title>、<p>、<a>等,与CSS和JavaScript配合使用,分别负责样式和交互性。示例代码展示了一个基本的HTML文档结构,包括标题、段落和链接。
|
30天前
|
弹性计算 前端开发 容器
HTML详解连载(8)
HTML详解连载(8)
|
30天前
|
XML 数据格式
HTML
HTML
28 1
|
10月前
|
移动开发 前端开发 UED
HTML详解连载(2)
HTML详解连载(2)
|
8月前
|
移动开发 前端开发 JavaScript
HTML基本讲解与使用
HTML基本讲解与使用
|
9月前
|
Web App开发 前端开发 JavaScript
HTML初识
HTML初识
72 0
|
10月前
|
前端开发 JavaScript
HTML详解连载(4)
HTML详解连载(4)
|
容器
认识HTML
认识HTML
|
存储 移动开发 JavaScript
HTML5介绍
简要介绍HTML5
108 0
|
XML 数据格式 开发者
html 4.01
html 4.01
100 0

热门文章

最新文章