简体   繁体   English

如何向 vuex 中 store.state 中嵌套 object 的正确键分派操作?

[英]How do I dispatch an action to the correct key of a nested object in store.state in vuex?

I have three buttons in my component that each have a specific data attribute so I can identify which button is clicked so I can then map the key to the correct property in the store state object.我的组件中有三个按钮,每个按钮都有一个特定的数据属性,因此我可以识别单击了哪个按钮,然后我可以 map 存储 state object 中正确属性的密钥。 Each button is identical except for the data attribute as follows:除了 data 属性之外,每个按钮都是相同的,如下所示:

<ul class="list-items">
            <li v-for="(value, index) in boxSizesArray" :key="index">
              <label for="oatmeal">oatmeal</label>
              <button
                id="oatmeal"
                type="button"
                class="date-buttons"
                :value="index"
                **data-cookie="oatmeal"**
                @click="selectBoxSize(value, $event)"
              >
                <div>
                  <p>{{ value.boxes }} boxes,</p>
                  <span>{{ value.cookieQty }} cookies</span>
                </div>
              </button>
            </li>
          </ul>

The event handler, selectBoxSize, is where I am mapping to a key and then trying to dispatch the action.事件处理程序 selectBoxSize 是我映射到键然后尝试分派操作的位置。 The first error that I have is that "property" throws an error as an unused var.我遇到的第一个错误是“属性”作为未使用的变量抛出错误。 I thought it could work as a key in "updateBoxSize" action.我认为它可以作为“updateBoxSize”操作的关键。 If my state object was flat, meaning chocolateChip, oatmeal, and campfire were not in the cookies object, I could set the correct value with: If my state object was flat, meaning chocolateChip, oatmeal, and campfire were not in the cookies object, I could set the correct value with:

this.$store.state.cookies[property] = cookieQty;

but I realize that that is not the correct way to mutate state.但我意识到这不是变异 state 的正确方法。

selectBoxSize({ boxes, cookieQty, price }) {
      const cookieKeys = {
        chocolateChip: "chocolateChip",
        oatmeal: "oatmeal",
        campfire: "campfire"
      };
     // I map over the object to match the attribute to the key I need in state.
      let element = event.currentTarget.getAttribute("data-cookie");
      for (let key in cookieKeys) {
        if (element === key) {
          let property = cookieKeys[element]; // currently get error, "property" -no unused vars
          this.updateBoxSize({ property: cookieQty });
        }
      }
    }

The updateBoxSize action and mutation in the store: store 中的 updateBoxSize 动作和突变:

mutations: {

    [UPDATE_BOX_SIZE](state, { cookieQty }) {
      this.state.cookies[cookie] = cookieQty;
    }
},
actions: {

    updateBoxSize({ commit }, { cookie: cookieQty }) {
      commit(UPDATE_BOX_SIZE, { cookie: cookieQty });
    }
}

and finally the state object最后是 state object


state: {
    daySelected: "",
    cookies: {
      chocolateChip: 0,
      campfire: 0,
      oatmeal: 0
    },
    userInfo: {
      userName: "",
      street: "",
      city: "",
      userPhoneNumber: ""
    },
    paid: false
  },

My overall question is since I can get the name of the key (the correct cookie) that I need to set for the quantity, how do I dispatch the action correctly with the correct structured payload.我的总体问题是,由于我可以获得需要为数量设置的键名(正确的 cookie),如何使用正确的结构化有效负载正确调度操作。 From there, what do I need to adjust for my action and mutation to work?从那里开始,我需要调整什么才能使我的动作和突变起作用?

You need to update your event handler, action and mutation.您需要更新您的事件处理程序、操作和突变。

Handler处理程序

       selectBoxSize({ boxes, cookieQty, price }) {
     //you already have the key as attribute, no need for loop. However, you might need to validate the key.
      let key = event.currentTarget.getAttribute("data-cookie");
       // note that am passing two properties 
          this.updateBoxSize({ key,  cookieQty });
        }
      

Store店铺

mutations: {

    [UPDATE_BOX_SIZE](state, { key,  cookieQty }) {
      this.state.cookies[key] = cookieQty;
    }
},
actions: {

    updateBoxSize({ commit }, { key, cookieQty }) {
      commit(UPDATE_BOX_SIZE, { key, cookieQty });
    }
}

Modify your function to be将您的 function 修改为

selectBoxSize({ boxes, cookieQty, price }) {
      let element = event.currentTarget.getAttribute("data-cookie");
          this.updateBoxSize({ key: element, val: cookieQty });
    }

and your store to be和你的商店

mutations: {

    [UPDATE_BOX_SIZE](state, payload) {
      this.state.cookies[payload.key]= payload.val;
    }
},
actions: {

    updateBoxSize({ commit }, payload) {
      commit(UPDATE_BOX_SIZE, payload);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VueX,$store.state 为空时怎么办 - VUEX, what to do when $store.state is null Vuex中状态变化时如何调度动作? - How to dispatch action whenever state changes in Vuex? 如何从动作分派另一个动作并在Vuex中分派另一个动作 - How to dispatch another action from an action and dispatch another action in Vuex 如何从另一个 Vuex 商店模块的另一个动作中分派一个动作? - How to dispatch an action from within another action in another Vuex store module? 状态对象未定义 Vuex 存储 - Vuex store is undefined for the state object [Vue警告]:渲染错误:“ TypeError:未定义不是对象(正在评估&#39;this。$ store.state&#39;)” - [Vue warn]: Error in render: “TypeError: undefined is not an object (evaluating 'this.$store.state')” Vuex和mysql连接对象:不要在变异处理程序之外变异vuex存储状态 - Vuex and mysql connection object: Do not mutate vuex store state outside mutation handlers 如果用户是真实的,如何使用 VUEX STORE state 在 vue.js 中将用户重定向到主页? - How to redirect user to home page if user is authentic i.e ID or PASSWORD is correct in vue.js using VUEX STORE state? 我可以从 Vuex 中的 getter 进行分派吗 - Can I do dispatch from getters in Vuex 如何在 vuex 中将 object 键/值对设置为初始 state - how to set object key/value pair to initial state in vuex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM