如何在vuex中修复'undefined'值?

时间:2019-08-19 10:30:41

标签: javascript vue.js vuex

我正在尝试将参数传递到我的路线,但是当它到达我的商店action时,它给了我undefined错误!

我尝试更改参数名称,也尝试将$route.params.id放在方法中并从那里调用它,但仍然无效!

As shown by vue-dev tools

Breakfast.vue

<router-link to="/menu/add/1" tag="h2" class="pull-right">Add Menu</router-link>

MenuAdd.vue

methods: {
  ...mapActions(['addMenu']),
  addMenuItem() {
    this.addMenu(this.menu, this.$route.params.typeId);
  }
}

router.js

{ path: '/menu/add/:typeId', component: MenuAdd }

状态

state: {
    menu: [],
    breakfastMenu: [],
    lunchMenu: [],
    dinnerMenu: []
  }

动作

addMenu: ({ commit }, { name, price, description }, typeId) => {
  commit('ADD_MENU', { name, price, description }, typeId);
  alert('Menu Successfully Added');
}

变异

'ADD_MENU': (state, { name, price, description }, typeId) => {
   state.menu.forEach((element) => {
     if (element.id == state.menu.length) {
       state.menu.push({
        id: element.id + 1,
        name: name,
        price: price,
        categoryId: typeId,
        description: description
       })
     }
   })
  }
}

我希望我的typeId工作并将参数发送到store.js,以便获得指定的结果

1 个答案:

答案 0 :(得分:0)

您只能将单个有效载荷传递给Vuex操作。

https://vuex.vuejs.org/api/#dispatch

此行试图传递两个有效载荷:

this.addMenu(this.menu, this.$route.params.typeId);

第二个参数将被视为options的{​​{1}}。这用于设置dispatch,此处与此无关。实际上,root: true只是被扔掉了。

您需要将两个参数包装到单个有效载荷对象中

typeId

在操作中,您可以使用类似以下内容将其拆开:

this.addMenu({ menu: this.menu, typeId: this.$route.params.typeId });

就我个人而言,这对于参数的构造是太多了,我可能会将其移到方法主体中。

相关问题