一位面试者提到直接调用vuex中mutations方法
簡(jiǎn)述是用this.$store.mutations.xxx(xx)方式調(diào)用,因從未見過此種調(diào)用方式,回來(lái)就搜索了一下,查詢結(jié)果如下
首先前文:
獲取 state 的方式有兩種,分別是?this.$store.state.num?這種直接獲取的方式,以及通過 getter 定義的方式獲取?this.$store.getter.num。
而修改 state 不能直接修改對(duì)象或者覆蓋對(duì)象的屬性,因?yàn)槲覀冏裱氖菃我粻顟B(tài)樹的管理原則,不允許通過?this.$store.state.num = 3?修改 state。
mutations:
定義的 mutations 對(duì)象將掛載到 Store 的 mutations 屬性上。
mutations 的每個(gè)屬性都是以方法的形式定義,默認(rèn)接收一個(gè)參數(shù),而這個(gè)參數(shù)實(shí)際上就是 Store 的 state 對(duì)象,只有在 mutations 的屬性中直接通過?state.xxx = xxx?修改 state。
mutations 的方法也不是直接通過?this.$store.mutations.xxx(xx)?去調(diào)用的,而是通過主動(dòng)觸發(fā)的。
可以打印?this.$store?查看 Store 的屬性,可以發(fā)現(xiàn), mutations 是以?_mutations?的私有屬性形式存在的,因此并不能直接調(diào)用(不能是指不允許)。
從上面的屬性列表中可以發(fā)現(xiàn)?commit?屬性,而這個(gè)屬性是一個(gè) function,用來(lái)觸發(fā) mutations 中定義的 mutation,所以可以通過commit方式觸發(fā)mutations中定義的方法
另外tips:?
1. commit方法穿參除默認(rèn)參數(shù)state外另一個(gè)參數(shù)是payload,且payload只支持一個(gè)參數(shù)
2.?mapMutations :
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)` ])} }?
一萬(wàn)個(gè)感謝讓我更深入認(rèn)知到mutations
?
轉(zhuǎn)載于:https://www.cnblogs.com/yl179578605/p/10646826.html
總結(jié)
以上是生活随笔為你收集整理的一位面试者提到直接调用vuex中mutations方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 神舟笔记本bios_海尔雷神(蓝天)神舟
- 下一篇: echart vue 图表大小_vue里