mapState、mapGetters、mapMutations、mapActions学习

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。mapState、mapGetters、mapMutations、mapActions学习,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

 

https://next.vuex.vuejs.org/zh/guide/state.html#mapstate-%E8%BE%85%E5%8A%A9%E5%87%BD%E6%95%B0

https://next.vuex.vuejs.org/zh/guide/getters.html#mapgetters-%E8%BE%85%E5%8A%A9%E5%87%BD%E6%95%B0

mapState和mapGetters都是用于简化开发,提高效率的工具

mapState、mapGetters、mapMutations、mapActions学习

 

 用法如下:

mapState、mapGetters、mapMutations、mapActions学习

 

 key(he、xuexiao、xueke)代表了函数名,value代表state中的对象。

mapState、mapGetters、mapMutations、mapActions学习

 

注意不要把…mapState放到methods中,这会导致vue将里面的识别成方法,在模板引擎中使用的时候也要加上括号如:{{ he() }}

mapGetters同理。

数组写法(名字要和state中的对象名称一致,也能达到同样效果):

mapState、mapGetters、mapMutations、mapActions学习

 

 

为什么都放到computed里面?

官方文档解释:由于 Vuex 的状态存储是响应式的,从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态

https://next.vuex.vuejs.org/zh/guide/state.html

https://segmentfault.com/q/1010000009696383

 

 

mapMutation:

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation(官方的vuex图也体现了这一点)。

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

官方案例:

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

要知道的事情:在vue的模板引擎中,写了方法但是开发者没有传参,vue会默认传一个event参数:

mapState、mapGetters、mapMutations、mapActions学习

 

 所以使用mapMutations时,会出现这种情况:

mapState、mapGetters、mapMutations、mapActions学习

 

 mapState、mapGetters、mapMutations、mapActions学习

 

 因为没有传参,所以mapMutations实际生成的代码是这样的:

mapState、mapGetters、mapMutations、mapActions学习

 

 可以改成这样,因为n在vc上:

mapState、mapGetters、mapMutations、mapActions学习

 

 也可以不修改模板引擎的内容,这样写也可以,和上面原理是一样的

mapState、mapGetters、mapMutations、mapActions学习

 

 上面都是对象写法,而数组写法都是相通的,即名字要相同

mapState、mapGetters、mapMutations、mapActions学习

 

 mapState、mapGetters、mapMutations、mapActions学习

 

mapActions同理 

mapState、mapGetters、mapMutations、mapActions学习

 

注意,这些都是状态共享,不算是组件间通信。

 

 

 

 

————恢复内容结束————

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/199822.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!