2๐
You can use arrays with your v-model
via v-model="timeSlot[index]"
. Now you can assign a specific value to timeSlot[index]
. Any changes made to this input are reflected in your array โ including removing it. You can also submit this data as an array to your server.
There is a caveat to using index
(ideally, the key should be something unique) in your loop to bind your data back to your array. While simple data like in the example should behave properly objects, or components, with complex data that need to be reactive may not be. You can check out this article for more info: https://deepsource.io/blog/key-attribute-vue-js/
new Vue({
el: '#app',
data: {
timeSlots: [],
},
methods: {
addSlot() {
this.timeSlots.push('');
},
removeSlot(index) {
this.timeSlots.splice(index, 1);
},
submit() {
// If using axios
axios.post('/your-endpoing', { timeslots: this.timeSlots })
.then(response => {
// Response from server
})
.catch(error => {
// Any erros
})
.finally(() => {
});
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(slot, index) in timeSlots" :key="index">
<input type="text" v-model="timeSlots[index]">
<button type="button" @click="removeSlot(index)">×</button>
</div>
<button type="button" @click="addSlot">Add Slot</button>
<h3>Output</h3>
<ul>
<li v-for="(slot, index) in timeSlots" :key="index">{{ slot }}</li>
</ul>
</div>
1๐
You can always create a variable which will hold the values and loop over it and bind the loop variable with v-model
like that
<template>
<div style="display: flex">
<div
v-for="(slot, key) in timeSlots"
:key="key"
>
<input
type="text"
v-model="slot.value"
/>
</div>
</div>
</template>
<script>
export default {
name: "App",
data: () => ({
timeSlots: [
{value: "600"},
{value: "1200"},
{value: "1500"}
]
}),
components: {
},
};
</script>
<style>
</style>