vuex学习总结

痞子三分冷 提交于 2019-11-27 18:33:29

State:全局状态


 

1:通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到 而不是在每个vue模块导入inport store 方式

2:mapState 辅助函数帮助我们生成多个计算属性 写法computed:mapState({})

3:映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组

  computed: mapState([

  // 映射 this.count 为 store.state.count
  'count'
])

4:对象展开运算符,直接合并computed原来的和现在的mapState

 

Getter:相当于store的计算属性


 

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

 

1:属性访问,this.$store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }],属于Vue响应系统组成部分,计算属性特征

2:  Getter 也可以接受其他 getter 作为第二个参数:使用场景不是太清楚

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

3:方法访问:你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。

 

4:mapGetters 辅助函数,将 store 中的 getter 映射到局部计算属性:使用方法同mapState,数组字符串、别名、扩展运算符

 

Mutation 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,必须同步方式


 

1:提交载荷(Payload):传递多余的参数,

store.commit('increment', 10) 提交简单字符串

store.commit('increment', {amount: 10}) 提交对象

store.commit({ type: 'increment', amount: 10}) 类型和参数一起提交

 

2:Mutation 需遵守 Vue 的响应规则

先初始化,添加新的属性的set方式,重新赋值,对象扩展符使用

 

3:使用常量替代 Mutation 事件类型,新增一个存放类型的模块,

import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'

const store = new Vuex.Store({
  state: { ... },
  mutations: {
    // 我们可以使用 ES2015 风格的计算属性命名功能来使用一个常量作为函数名
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})

 

4:在组件中提交 Mutation,

a:你可以在组件中使用 this.$store.commit('xxx') 提交 mutation,

b:或者使用 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')`
    })
  }
}

 

 

 Action异步操作:

        Action 类似于 mutation,不同在于:

 

  • Action 提交的是 mutation,然后mutation去更改状态,而不是直接变更状态。
  • Action 可以包含任意异步操作。

 

 


 

 

 

 

 

 

 

 

 

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!