Home > Software engineering >  Input number to add new text box Vue3
Input number to add new text box Vue3

Time:10-29

I want to try handle add new inutbox. I try to follow this example example

My code

    <DialogTitle as="h3" >Transaction #1</DialogTitle>
   <input type="text"  v-model="inputs.sequence" @inputs='$emit("update:modelValue", inputs)'  />


export default {
  name:'prize-editor',
  components: {
    DropImages,
    date,
    DialogTitle
  },
  props:{
    modelValue:Object
  },
  setup(props){
    let inputs = ref({
      detail:'',
      name:'',
      startDate:'',
      sequence:'',
      rewardId:'',
      imageUrl:"",
    })

    onMounted( () => {
      inputs.value=props.modelValue
    });
    watch(props.modelValue, (value) => {
      inputs.value = value
      console.log('watch',value)
    })
    return{
      inputs,  
    }
  },
};

CodePudding user response:

You have given little info about how those inputs are supposed to behave exactly, but if we imagine you want to store (and do something with) the value of each, you need an array. and a function that adds as many elements to that array as you put in the input (how you call the function is up to you):

addInput(number) {
  for(let i = 0; i < number; i  ) {
    this.inputArray.push({ value: "" });
  }
}

Then you need to use v-for to render inputs based on your array :

<input v-for="(input, index) in inputArray" :key="index" v-model="input.value" type="text" />

To access the elements you can use index (like inputArray[2].value for the third input's value).

CodePudding user response:

This would be a full vue component with your what you want, note that its based on options api and has no styles, those are on yourself:

<template>
  <div>
    <input type="text" v-model="inputCounter" />
    <button @click="setInputs">Set</button>
    <input v-for="(input, index) in inputs" :key="index" v-model="input.value" type="text" />
  </div>
</template>

<script>
export default ({
  data() {
    return {
      inputCounter: "",

      inputs: []
    }
  },

  methods: {
    setInputs() {
      for(let i = 0; i < parseInt(this.inputCounter); i  ) {
        this.inputs.push({ value: "" });
      }
    }
  }
})
</script>
  • Related