如何修复 vuex 中的“未定义”值?

ext*_*boy 3 javascript vue.js vuex

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

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

如图vue-dev工具所示

早餐.vue

<router-link to="/menu/add/1" tag="h2" class="pull-right">Add Menu</router-link>
Run Code Online (Sandbox Code Playgroud)

菜单添加.vue

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

路由器.js

{ path: '/menu/add/:typeId', component: MenuAdd }
Run Code Online (Sandbox Code Playgroud)

状态

state: {
    menu: [],
    breakfastMenu: [],
    lunchMenu: [],
    dinnerMenu: []
  }
Run Code Online (Sandbox Code Playgroud)

行动

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

突变

'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
       })
     }
   })
  }
}
Run Code Online (Sandbox Code Playgroud)

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

ski*_*tle 5

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

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

该行尝试传递两个有效负载:

this.addMenu(this.menu, this.$route.params.typeId);
Run Code Online (Sandbox Code Playgroud)

第二个参数将被视为optionsfor dispatch。它用于设置root: true,这里不相关。实际上,它们typeId只是被扔掉了。

您需要将两个参数包装到一个有效负载对象中:

this.addMenu({ menu: this.menu, typeId: this.$route.params.typeId });
Run Code Online (Sandbox Code Playgroud)

在操作中,您可以使用以下方法将其拆开:

addMenu: ({ commit }, { menu: { name, price, description }, typeId }) => {
Run Code Online (Sandbox Code Playgroud)

就我个人而言,这对于我的口味来说有点太多的参数解构,我可能会将它移到方法体中。