hello I try to generate a decision tree when the user chooses a reason option that generates the reasons and we create a select, if he clicks on an option and the API does not return an empty array another select below with sub-reasons which is created all this is dynamically created according to the response of the API as long as it does not return an empty array and so on
<template>
// the first select option don't generate
<select v-model="reasonOne" @change="eventOne(reasonOne)">
<option
v-for="(reason, key) in reasonsOne"
:key="key"
:value="reason.value"
:selected="reason.item === reasonOne"
@click="eventOne(reason.item)"
>
{{ reason.item }}
</option>
</select>
// the div with generate dynamically all select option
<div v-if="showSav">
<div id="select-pattern" />
</div>
<template/>
<script>
async eventOne(option) {
let reasonsReturn = await customerApi.getReturnPattern(
app,
this.detailReturn.sku.product.id
);
if (!this.reasonsReturn.length) {
this.showSav = false;
}
let selectPattern = document.createElement('select');
let target = document.getElementById('select-pattern');
selectPattern.className = 'select-create';
selectPattern.id = 'create-input';
target.appendChild(selectPattern);
for (let item of reasonsReturn) {
let optionPattern = document.createElement('option');
optionPattern.value = item.id;
optionPattern.text = item.name;
selectPattern.appendChild(optionPattern);
}
document
.getElementById('create-input')
.addEventListener('change', async function () {
let reasonData = await customerApi.getReturnPattern(
app,
this.value
);
});
}
</script>
I was able to create the first select with it but the rest I am stuck I think we have to make a loop on select which will be created if the API returns data. i don't know how to do it while calling the api every time when the option changes
CodePudding user response:
To create something dynamically the easiest way is to use a v-for
. I could not reproduce your code, but I can show you how the structure is looking:
TEMPLATE:
Just use a v-for
and loop over it for every input
you will create (here it's created after clicking on a button)
<div v-for="item in inputs" :key="item.id">
<!-- HERE YOU CAN PUT YOUR SELECTION -->
</div>
<b-button @click="addNewInput()">Add new Input</b-button>
SCRIPT:
Two things to do in your script. First: Define your data and create first input
and than add a method for your click-event
and push
a input every time clicking on the button.
data() {
return {
id: 1,
//following is your first input
inputs: [{
id: this.id = 1, //count 1 for every input -> ID IS UNIQUE
}]
}
},
methods: {
addNewInput() {
this.inputs.push({
id: this.id = 1
})
}
}
That's the structe you can do it with a click-event
or with a for-loop
inside of your methods but the structer stays always the same!
Hopefully this helps you out!