[英]I have to make an array of strings from multiple inputs in Vuejs. How can I go about this?
您可以通過v-model="timeSlot[index]"
將 arrays 與v-model
一起使用。 現在您可以為timeSlot[index]
分配一個特定的值。 對此輸入所做的任何更改都會反映在您的數組中——包括刪除它。 您還可以將此數據作為數組提交到您的服務器。
在循環中使用index
(理想情況下,鍵應該是唯一的)將數據綁定回數組需要注意。 雖然像示例中這樣的簡單數據應該表現正確的對象或組件,但需要反應的復雜數據可能不是。 您可以查看這篇文章了解更多信息: 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>
您始終可以創建一個變量來保存值並對其進行循環並將循環變量與v-model
綁定,就像這樣
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.