Fajel
Fajel

Reputation: 3

Push component in vue

I've been trying to push a text field whenever the "add button" is pressed. This is my code so far.

<v-container fluid>
        <v-row>
          <v-col cols="7">
            <v-row class= "mx-1 my-1">
              <v-text-field outlined label="Test 1" v-model="test1"></v-text-field>
            </v-row>
          </v-col>
          <v-col cols="5">
            <v-row class= "mx-4 my-1">
              <v-text-field type="number" outlined label="Test 2" v-model="test2"></v-text-field>
            </v-row>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12">
            <v-row class= "mx-1 my-n8">
              <v-btn
              @click="doWork()" 
              width = 100%
              small
              outlined
              color="#0000b0" 
              >
              <v-icon dark>mdi-plus</v-icon></v-btn>
            </v-row>
          </v-col>          
        </v-row>
      </v-container>

Here is my javascript

<script>
export default {
    data () {
      return {
        test1:'',
        test2:''
      }
    },
    methods: {
      doWork () {
        //just for debugging purposes
        console.log(this.valor)
        console.log(this.precio)
      }
    }

}
</script>

What should I add in the "doWork()" method in order to push another pair of text fields

Thanks in advance <3

Upvotes: 0

Views: 346

Answers (1)

Zooly
Zooly

Reputation: 4787

You can transform your fields into a fields array:

data () {
  return {
    inputs: []
  }
}

Your addWork method becomes a method that push a new value in this inputs array:

methods: {
  doWork () {
    this.inputs.push({
      label: 'Test',
      value: ''
    })
  }
} 

And you display those inputs with a v-for directive:

<v-row>
  <v-col cols="2" v-for="(input, index) in inputs" :key="index">
    <v-row class="mx-1 my-1">
      <v-text-field outlined :label="input.label" v-model="input.value"></v-text-field>
     </v-row>
   </v-col>
 </v-row>

Working example: https://codesandbox.io/s/festive-dream-gbo6t?file=/src/App.vue

Upvotes: 1

Related Questions