thiebo
thiebo

Reputation: 1435

vuejs Props are readonly

I'm new to Vue and learning Vuejs 3. I have a list of tasks. I want show that list and a span at the end of each line, so the line gets deleted by clicking on that span.

I have this code for createApp:

const babies = Vue.createApp({
    data(){
        return{
            tasks:[
                {id: 0,kid:'Sabina',tache:'eductate'}
                {id: 1,kid:'Henry',tache:'listen'}
           ]
        }
    },
    components:{
        'listbabies':Compodeux
    },
    methods:{
        supprimer(ido){
            this.tasks = Object.values(this.tasks).filter(item => item.id !== ido)
        }    
    }
})

and the component contains this:

const Compodeux=('listbabies',{
    props:{
        tasks:{
            type: Object
        },
        suppr:{
            type: Function
        }
    },
    data(){
        return{
            line:"line_" + this.tasks.id
        }
    },
    template:
        `<div :id=this.ligne>
            <div id="ligne_credits">
                <span> {{tasks.kid}} </span>
                <span> {{tasks.tache}} </span>
                <span  @click="$emit(this.supprimer(taches.id))" :id="taches.id"> [*] </span>
            </div>
        </div>
        `
})

All this code works fine, but for the @click in the component template. I get an error message: this.supprimer is not a function

Upvotes: 4

Views: 14168

Answers (3)

Gabriel soft
Gabriel soft

Reputation: 563

The answer to this question is on the vue doc, since props update data one-way.

According to the vue doc;

When objects and arrays are passed as props, while the child component cannot mutate the prop binding, it will be able to mutate the object or array's nested properties. This is because in JavaScript objects and arrays are passed by reference, and it is unreasonably expensive for Vue to prevent such mutations. The main drawback of such mutations is that it allows the child component to affect parent state in a way that isn't obvious to the parent component, potentially making it more difficult to reason about the data flow in the future. As a best practice, you should avoid such mutations unless the parent and child are tightly coupled by design. In most cases, the child should emit an event to let the parent perform the mutation.

Upvotes: 0

FloWy
FloWy

Reputation: 984

Use a custom event by defining the name in the emit function.

@click="$emit('supprimer', taches.id)

And then you need to catch the event in the parent components template.

<template>
  <MyChildComponent @supprimer="supprimer" />
</template>

For more details, check the docs.

Upvotes: 4

Emad Malekpour
Emad Malekpour

Reputation: 38

Try @click="$emit("supprimer" , taches.id)" instead of @click="$emit(this.supprimer(taches.id))"

Upvotes: 0

Related Questions