登录
原创

vuex的基本使用以及如何向dispatch传递多个参数

发布于 2020-10-31 阅读 22431
  • Vue.js
  • Vuex
原创

1. 什么是vuex

  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
  • 状态管理中包含一下几点:
    state,驱动应用的数据源;
    view,以声明方式将 state 映射到视图;
    actions,响应在 view 上的用户输入导致的状态变化。

2. 使用vuex

image.png

3.使用mutations修改state(同步)

image.png

4.使用dispath修改state(异步)

image.png

5.mutations和dispath的存值以及取值:

  • mutations:
// 修改:
this.$store.commit('initUserInfo',friend);

// 取值:
this.$store.state.userInfo;
  • dispath:
// 修改:
this.$store.dispatch('initUserInfo',friend);

// 取值:
this.$store.getters.userInfo;

5.给vuex dispatch传递多个参数

  • 载荷Payload
    在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation会更易读。
   this.$store.dispatch("changeComps", {
            comps: this.comps,
            allPluginsComps: this.allPluginsComps,
          });
  • 对象Object
  this.$store.dispatch({
            type:"changeComps", 
            comps: this.comps,
            allPluginsComps: this.allPluginsComps,
          });

PS:多参数封装为Object类型放在第一或者第二个参数里就好了。

评论区

timing
4粉丝

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0

举报