programing

Vuex에서 여러 페이로드 추가

javaba 2022. 8. 8. 18:30
반응형

Vuex에서 여러 페이로드 추가

2개의 데이터, 금액, ID를 스토어에 전달하고 싶기 때문에 Actions에 2개의 payload를 부여하려고 하는데 동작하지 않습니다.두 데이터 모두 정의되지 않았습니다.

같은 이벤트에서 2개의 payload를 전달하려면 어떻게 해야 합니까? (console.logs 위치에 payload를 찾을 수 있습니다.)

1개의 payload(id 또는 량)를 넣었을 때 올바른 값을 얻었지만 2개의 payload를 주려 할 때는 그렇지 않습니다.

잘 부탁드립니다!

여기 내 컴포넌트가 있습니다.

    <script>
import { mapActions } from 'vuex'
import BaseButton from './BaseButton.vue'

export default {

  name: 'MenuItem',
  components: {
    BaseButton
  },
  props: {
    image: {
      type: Object,
      required: true
    },
    inStock: {
      type: Boolean,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      required: true
    },
    quantity: {
      type: Number,
      defaut: 1
    },
    id: {
      type: Number,
      defaut: 1
    }
  },
  data() {
    return {
      onSale: false
    }
  },
  computed: {
    generatedPrice() {
      if (this.onSale) {
        return (this.price * 0.9).toFixed(2)
      } else {
        return this.price
      }
    }
  },
  methods: {
    ...mapActions(['updateShoppingCart'])
  },
  beforeMount() {
    const today = new Date().getDate()

    if (today % 2 === 0) {
      this.onSale = true
    }
  }
}

</script>

<template>
  <div class="menu-item">
    <img class="menu-item__image" :src="image.source" :alt="image.alt" />
    <div>
      <h3>{{ name }}</h3>
      id : {{ id }}
      <p>Price: {{ generatedPrice }} <span v-if="onSale">(10% off!)</span></p>
      <p v-if="inStock">In Stock</p>
      <p v-else>Out of Stock</p>
      <div>
        <label for="add-item-quantity">Quantity: {{ quantity }}</label>
        <input v-model.number="quantity" id="add-item-quantity" type="number" />
        <BaseButton @click="updateShoppingCart(quantity, id)" class="test">
          Add to shopping cart
        </BaseButton>
      </div>
    </div>
  </div>
</template>

스토어:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    restaurantName: 'Cafe with A Vue',
    shoppingCart: 0,
    selectedItemId: 0,
    croissiantNumber: 0,
    baguetteNumber: 0,
    eclairNumber: 0,
    simpleMenu: [
      {
        id: 1,
        name: 'Crossiant',
        image: {
          source: '/images/crossiant.jp',
          alt: 'A crossiant'
        },
        inStock: true,
        quantity: 1,
        price: 2.99
      },
      {
        id: 2,
        name: 'French Baguette',
        image: {
          source: '/images/french-baguette.jpe',
          alt: 'Four French Baguettes'
        },
        inStock: true,
        quantity: 1,
        price: 3.99
      },
      {
        id: 3,
        name: 'Éclair',
        image: {
          source: '/images/eclair.jp',
          alt: 'Chocolate Éclair'
        },
        inStock: false,
        quantity: 1,
        price: 4.99
      }
    ]
  },
  getters: {
    copyright: state => {
      const currentYear = new Date().getFullYear()

      return `Copyright ${state.restaurantName} ${currentYear}`
    }
  },
  mutations: {
    ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, {amount}) {
      state.shoppingCart += amount
    }
  },
  actions: {
    updateShoppingCart({ commit }, {amount, id}) {
      commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', {amount, id})
      console.log(id)
      console.log(amount)
    }
  },
  modules: {}
})

질문 1

은 두 가지합니다. 즉, 두 가지 속성을 가진 오브젝트입니다.amount ★★★★★★★★★★★★★★★★★」id그러나 오브젝트를 전달하지 않고 두 개의 다른 변수를 전달하고 있습니다.updateShoppingCart(quantity, id).

템플릿에서는 대신 다음과 같이 호출합니다.

updateShoppingCart({ amount: quantity, id });  // Note the object brackets

이름을 ""로 변경합니다.quantity에서 ★★★★★★★★★★★에amount★★★★★★★★★★★★★★★★★★★★★★★★★★★

updateShoppingCart({ amount, id });

질문 2(파괴 사용)

변환:

ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, { amount, id }) {
  state.shoppingCart += amount;
  console.log(id);
}

액션:

updateShoppingCart({ commit }, { amount, id }) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', { amount, id })
  console.log(id)
  console.log(amount)
}

질 2b 사용)payload

변환:

ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, payload) {
  state.shoppingCart += payload.amount;
  console.log(payload.id);
}

액션:

updateShoppingCart({ commit }, payload) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', payload)
  console.log(payload.id)
  console.log(payload.amount)
}

언급URL : https://stackoverflow.com/questions/60317949/add-multiple-payloads-on-vuex

반응형