vuex-2-mapMutations-strict严格模式

简介: 官方文档真的写的 挺清楚的 ,简易 在去多看看 官网

1.前言


官方文档真的写的 挺清楚的 ,简易 在去多看看 官网


2.mapMutations 概念


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

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数


3. 提交载荷(Payload)


载荷理解成 参数就行


// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}

使用


store.commit('increment', 10)

载荷 最好是一个对象,这样可以包含多个字段并且记录的 mutation 会更易


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

使用


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



4. 对象风格的提交方式


commit() 的参数直接是个对象


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

当使用对象风格的提交方式,整个对象都作为载荷传给 mutation 函数,因此 handler 保持不变


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



5.使用常量替代 Mutation 事件类型


mutation-types.js


export const SOME_MUTATION = 'SOME_MUTATION'

store.js


import Vuex from 'vuex'
import { SOME_MUTATION } from './mutation-types'
const store = new Vuex.Store({
  state: { ... },
  mutations: {
    [SOME_MUTATION] (state) {
      // mutate state
    }
  }
})



6.组件中使用 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')`
    })
  }
}


这是什么意思呢 截个图意思 意思哈哈

`1{(IY@4GK9LQS{_S][P_8S.png

mutaions.png


7.   严格模式


这个时候肯定有人写的不标准, 直接访问修改也没报错


this.$store.state.hotState = res.data


那就启用严格模式

strict:true

在 store里面配置


export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    user
  },
  strict:true
})

这个时候写法不标准 ,不通过commit进行修改,控制台就会红彤彤




相关文章
|
9天前
|
JavaScript 前端开发 安全
JS 严格模式和正常模式的区别
JS 严格模式和正常模式的区别
|
1月前
|
JavaScript 前端开发 安全
javascript中的严格模式(use strict)
javascript中的严格模式(use strict)
21 1
|
1月前
|
安全 JavaScript 前端开发
和为严格模式
和为严格模式
|
1月前
|
监控 JavaScript 前端开发
未使用 “严格模式“(js的问题)
未使用 “严格模式“(js的问题)
12 0
|
1月前
|
JavaScript 前端开发 安全
Typescript 严格模式有多严格?
Typescript 严格模式有多严格?
|
8月前
|
JavaScript
vue3如何关闭严格模式
vue3如何关闭严格模式
395 0
|
10月前
|
JavaScript 前端开发
JS严格模式详解
JS严格模式详解
152 0
|
JavaScript 前端开发 编译器
ES6 —— 严格模式
ES6 —— 严格模式
110 0
|
JavaScript 前端开发 安全
为什么使用严格模式
为什么使用严格模式:
54 0
|
Web App开发 JavaScript 前端开发
JavaScript 严格模式(use strict)
JavaScript 严格模式(use strict)
66 0