Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

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

enter image description here

The above picture is how it looks like.

Now, from every input time value, I have to create an array: timeSlots:["600", "1200", "1500"] like so, when submit is clicked.

I know I can data bind each input using v-model, and then when submit is clicked I can loop over them and add them to an array.

But is there a better way to this, especially using v-for ?

For example, if I have like 40 slots, having 40 data variables doesn't look great in the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)">&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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...