vuex-笔记

如何在组件中使用 全局属性

  1. mapState方式
import { mapState } from 'vuex'

将全局状态共享为当前组建的计算属性

computed: {
  ...mapState(['count'])
}
  1. this.$store.state.count 的方式

mutation

用于变更state中的数据(!!!更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。)

为了集中维护

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

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

mutation 中不能执行异步操作

action

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

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

Action 通过 store.dispatch 方法触发

store.dispatch('increment')

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

VSCODE 使用 .prettierrc 格式化配置

posted @ 2021-04-08 18:43  大毛线|dmx  阅读(47)  评论(0)    收藏  举报