0

I just started learning vue.js and have encountered a problem I can't solve. I made a few researches and found this stack overflow post, that is about the same problem : Vue 2 - Mutating props vue-warn. But couldn't solve it...

I tried this.$emit('update:onSale', true), but it didn't seam to work. Could you please help me?

Find below the script that is not working properly:

<script>
export default {
    name: "MenuItem",
    props: ["addToShoppingCart", "image", "inStock", "name", "price", "quantity"],
    data() {
        return {
            onSale: false
        }
    },
    computed: {
        generatedPrice() {
            if (this.onSale) {
                return (this.price * 0.9).toFixed(2)
            } else {
                return this.price
            }
        }
    },
    beforeMount() {
        const today = new Date().getDate()

        if (today % 2 === 0) {
            this.onSale = true
            //this.$emit('update:onSale', true)
        }
    }
}
</script>

<template>
    <div class="menu-item">
        <img class="menu-item__image" :src="image.source" :alt="image.alt" />
        <div>
            <h3>{{ name }}</h3>
            <p>Prix : {{ generatedPrice }}</p>
            <p v-if="inStock">En stock</p>
            <p v-else>En rupture de stock</p>
            <div>
                <label for="add-item-quantity">Quantité : {{ quantity }}</label>
                <input v-model.number="quantity" id="add-item-quantity" type="number" />
                <button @click="addToShoppingCart(quantity)">
                    Ajouter au panier
                </button>
            </div>
        </div>
    </div>
</template>

<style></style>

I thank you in advance for your help,

Kaerbran
  • 65
  • 8
  • 1
    Obviously some code missing like the parent component of the MenuItem that passes the props. If you have your project repository in GitHub, and the project is not large and complex, import it into CodeSandbox and post the link here in order to make it easier for others to analyze. – Tim Aug 13 '21 at 14:55
  • You are using a prop as the value in a v-model which will try to edit it, which isn't allowed. You should assign the value of the prop to a variable in `data` first, then use that 'copy'. – match Aug 13 '21 at 18:28

1 Answers1

0

you this line is the culprit.

 <input v-model.number="quantity" id="add-item-quantity" type="number" />

here, you are assigning quantity to v-model. and v-model tends to update it. Which is against the rules. i.e. a prop can only be updated by its creator component. And MenuItem is certainly not the creator.

To fix this, create a data variable:

data() {
  return {
    qty: this.quantity
  }
}

and

<input v-model.number="qty" id="add-item-quantity" type="number" />
Rahul
  • 5,346
  • 5
  • 32
  • 87