staxwell staxwell - 18 days ago 5
Javascript Question

Deleting dynamic input fields in Vue

Noob question but I can get fields to render in Vue but not sure how to delete my fields. I added an index option in the

v-for
directives but not sure what to do after that. Thanks!

Here is a working JSFiddle: https://jsfiddle.net/xu55npkn/

<body>

<div id="app"></div>

<script>

const createNewOption = () => {
return {
text: '',
isAnswer: false
}
}

const createNewQuestion = () => {
return {
text: '',
options: [createNewOption()]
}
}

var vm = new Vue({
el: '#app',
template: `<div class="quiz-builder container">
<div v-for="question in questions">
<div class="input-group">
<input type="text" class="form-control" v-model="question.text" placeholder="Enter a question">
<span class="input-group-btn">
<button class="btn btn-danger" type="button">X</button>
</span>
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" @click="addOption(question)">Add an option</button>
</span>
</div>
</br>
<div class="input-group" v-for="(option, index) in question.options" style="margin-bottom: 20px">
<span class="input-group-addon">
<input type="checkbox" v-model="option.isAnswer">
</span>
<input type="text" class="form-control" v-model="option.text" placeholder="Enter an option">
<span class="input-group-btn">
<button class="btn btn-danger" type="button">X</button>
</span>
</div></br>
</div>
<button class="btn btn-default" @click="addQuestion" :disabled="questions.length >= 5 ? true : false">
Add another question
</button>
<button class="btn btn-primary" style="background-color: #ffcc00; border: #ffcc00">
Create quiz
</button>
</div>`,
data () {
return {
questions: [createNewQuestion()],
showQuestions: false,
}
},
methods: {
addQuestion () {
this.questions.push(createNewQuestion())
},
removeQuestion (index) {
this.questions.shift(index)
},
addOption (question) {
question.options.push(createNewOption())
}
}
})

</script>




Answer

Based on your updated question, you have already solved for removing questions, although yev's answer is a much better way for removing questions.

To remove options, you need to add a new handler for removeOption that takes in both the question (which you are iterating over) and the option (which you are iterating over. Vue handles both of these scenarios for you. You can then find the index of the option and splice the array. See this fiddle.

template:

<button class="btn btn-danger" type="button" @click="removeOption(question, option)">
    X
</button>

component:

removeOption (question, option) {
    var index = question.options.indexOf(option);
    if (index > -1) {
        question.options.splice(index, 1);
    }
}