In my code, I have implemented a watcher to monitor the dropdown value. If the value is equal to "select", a new array named "option" is created with one element. There is a button that allows adding a value to the array when the dropdown value is "select". The button function works fine, but the input field that should display the array values doesn't update after the button click. Apologies for my poor explanation. Below is the code snippet:
<template lang="pug">
.formHolder
.quest
input(type="text" placeholder="Question" v-model="tempForm.tempQuestions[0].question")
input(type="text" placeholder="Description" v-model="tempForm.tempQuestions[0].description")
select(name="category" v-model="tempForm.tempQuestions[0].type")
option(value="text") text
option(value="select") Dropdown
option(value="number") Number
This input field is responsible for looping through the array:
.option(v-for="(option, index) in tempForm.tempQuestions[0].options")
input(type="text" placeholder="Option" v-model="tempForm.tempQuestions[0].options[index]")
This button adds a value to the array:
button(v-if="tempForm.tempQuestions[0].type === 'select'" @click="addItems") Add Options
</template>
<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
export default {
name: "HomeView",
components: {
HelloWorld,
},
data() {
return {
questions: 0,
tempForm: {
tempQuestions: [
{
question: null,
description: null,
type: null,
},
],
},
form: {
questions: [],
},
};
},
methods: {
addQuestion() {
this.tempForm.tempQuestions.push({
question: null,
description: null,
type: null,
});
this.questions++;
this.readerNos++;
},
addOptionArray() {
this.tempForm.tempQuestions[0].options.push("");
},
//////// This is the function
addItems() {
console.log(this.tempForm.tempQuestions[0].options);
let length = this.tempForm.tempQuestions[0].options.length;
console.log(length);
this.$set(this.tempForm.tempQuestions[0].options, length, "");
},
},
watch: {
tempForm: {
handler: function () {
this.tempForm.tempQuestions.forEach((question) => {
if (question.type === "select") {
question.options = [];
question.options.push("");
} else if (question.type === "text") {
if (question.options) {
delete question.options;
}
} else if (question.type === "number") {
if (question.options) {
delete question.options;
}
}
});
},
deep: true,
},
},
};
</script>