zoukankan      html  css  js  c++  java
  • Vuex中mutations和actions传参写法

    1.vuex中mutations如何传多个参数

        1.传一个参数写法

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

        2.传多个参数写法

    mutations: {
      increment (state, payload) {
        state.count += payload.amount1;
        state.count += payload.amount2;
        state.count += payload.amount3;
        state.count += payload.amount4;
    } }
    
    
    store.commit('increment', {
      amount1: 10,
      amount2: 20,
      amount3: 30,
      amount4: 40,
    }

    2.vuex中actions参数

        1.一般写法:

    actions:{
        add_num({commit}){
            console.log({commit})
            setTimeout(() => {
                commit('change',100);
            },2000)
        }
    }

        2.{commit}代表什么

          action函数可以接收一个与store实例具有相同方法的属性context,这个属性中包括如下:

     context:{
            state,   等同于store.$state,若在模块中则为局部状态
            rootState,   等同于store.$state,只存在模块中
            commit,   等同于store.$commit
            dispatch,   等同于store.$dispatch
            getters   等同于store.$getters
    }
    
    常规写法调用的时候会使用context.commit,但更多的是使用es6的变量解构赋值,也就是直接在参数的
    位置写自己想要的属性,如:{commit}。

        3.传自定义参数,一个或多个方法同mutations方式相同

    3.vuex 中dispatch 和 commit 的用法和区别

        dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('action方法名',值)

        commit:同步操作,写法:this.$store.commit('mutations方法名',值)    

        使用dispatch 和 commit的区别在于,前者是异步操作,后者是同步操作,所以 一般情况下,推荐直接使用commit,即 this.$store.commit(commitType, payload),以防异步操作会带来的延迟问题

        异同点:

          1.同: 能够修改state里的变量,并且是响应式的(能触发视图更新)

          2.异:

            若将vue创建 store 的时候传入 strict: true, 开启严格模式,那么任何修改state的操作,只要不经过mutation的函数,vue就会  throw error :    [vuex] Do not mutate vuex store state outside mutation handlers

        结论: 官方推荐最好设置严格模式,并且每次都要commit来修改state,而不能直接修改state,以便于调试等。

  • 相关阅读:
    eclipse转ieda新手教程之-如何从svn导入一个 Maven 项目到 IntelliJ IDEA 2017
    从svn下载maven项目到ieda
    Maven的下载、安装与配置
    java.lang.NoClassDefFoundError: com/google/common
    guava.jar下载
    js,时间格式的验证
    为什么String类型的日期,传到前台变成数字了
    java&oracle日期查询
    java空指针异常
    java获取当前时间的第二天
  • 原文地址:https://www.cnblogs.com/yxkNotes/p/12751869.html
Copyright © 2011-2022 走看看