簡體   English   中英

我必須從 Vuejs 中的多個輸入中創建一個字符串數組。 我怎么能 go 關於這個?

[英]I have to make an array of strings from multiple inputs in Vuejs. How can I go about this?

在此處輸入圖像描述

上圖是它的樣子。

現在,從每個輸入時間值,我必須創建一個數組: timeSlots:["600", "1200", "1500"] 就像這樣,當單擊提交時。

我知道我可以使用 v-model 對每個輸入進行數據綁定,然后當單擊提交時,我可以遍歷它們並將它們添加到數組中。

但是有沒有更好的方法,尤其是使用 v-for?

例如,如果我有 40 個插槽,那么有 40 個數據變量在代碼中看起來並不好。

您可以通過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)">&times;</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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM