简体   繁体   中英

Deleting object in Vue.js

I've got a problem and need help. Im trying to teach in Vue.js. I'm doing a quiz and i want to put here a button with deleting a question. I tried this:

        deleteQuestion(index) 
    {        
        this.questions.splice(index, 1);
    }

but it will delete always only first question although when i want to delete second question. Any help?

Full Code:

HTML:

            <div class="question" v-for="question in questions">
            <!-- Znění otázky -->
            <h2>{{ question.question }}</h2><button @click="deleteQuestion" class="doprava"><img src="criss.png"/></button>
            <!-- Odpovědi -->
            <label v-for="answer in question.answers" class="answer" :class="{ 'answer-correct':answer.correct, 'answer-false':answer.false }">
                <input type="checkbox" :value="answer.id" v-model="question.selected"> {{ answer.answer }}
            </label>
        </div>
        <hr>
        <button @click="onSubmit()">onSubmit</button>

JS:

var vm = new Vue({
el: "#app",
data: {
    questions: questions,
    result: 0
},
methods: {
    onSubmit() {
        this.result = 0

        this.questions.forEach(question => {
            question.answers.forEach(answer => {
                answer.correct = question.correct.includes(answer.id);
                answer.false = question.false.includes(answer.id);
            });
        });
    },
    deleteQuestion(index) 
    {        
        this.questions.splice(index, 1);
    }
}

});

You haven't passed an index to your deleteQuestion method. Try this in your template instead:

<div class="question" v-for="(question, index) in questions">
  <h2>{{ question.question }}</h2>
  <button @click="deleteQuestion(index)" class="doprava">
    <img src="criss.png"/>
  </button>

etc.

However a better option might be to give each question an id property and delete it by filtering agains that id instead. This is because you can't guarantee that the order/index of questions in the template will be consistent on each re-render. This could be done like so:

<button @click="deleteQuestion(question.id)">

Then in your method:

deleteQuestion(id) {
  this.questions = this.questions.filter(q => q.id !== id);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM