-2

I am trying to initialize Vue data() with a value in rendered input tag. I know it is possible to make input tag value to get data from data() using v-model="[data-key-here]" in Vue. Is there any way to initialize data in data() using data that is a value of an input tag in Vue?

Code Sample

<template>
  <input v-model="car_name">
  <input v-model="car_weight" value="40">
</template>

<script>
  export default{
    data(){
      return{
        car_name: "Range Rover",
        car_weight: null
      }
    }
  }
</script>
Valentine Sean
  • 79
  • 3
  • 13
  • Can you share a code example to elaborate on what you mean to ask? – Keith M Apr 10 '21 at 11:57
  • @KeithM, I am looking for a way to initialize **car_weight** in **script** tag using that value=40 inside of **input** tag – Valentine Sean Apr 10 '21 at 14:03
  • Can you actually access the html input element before the data() in vue is initialised? If not (as I suspect), then as you mentioned, the input tag value ( using v-model="car_weight") can come from the data. I don't understand how / why you would need to do otherwise... To do what you want, remove the "value" tag from the input and put the value into the data structure in Vue data: car_weight: 40 – richter Apr 10 '21 at 14:17
  • I understand what you are saying, but the logic I have is **input** value is initially set using a method in a parent component, then I want either that method to initialize child's (form's) data or **input** value to initialize data consistently. I am looking for a way to achieve this, I do not know if it is possible. – Valentine Sean Apr 12 '21 at 07:50

2 Answers2

0

As I understand it, the DOM will be rendered based on the vuejs data model. In order to set the value of the input field, you can initialise the VueJs data (in your case 'car_weight') and dispense with the "value" tag on the input element. Later, when you change the input, the VueJs data will be updated to reflect this, so:

<template>
  <input v-model="car_name">
  <input v-model="car_weight">
</template>
<script>
  ...
  data () {
    return {
      car_name: "Holden",
      car_weight: 40
    }
  }
</script>

.. will give you your initial value, and when you change the input in the browser, the data will be updated.

richter
  • 441
  • 4
  • 8
0

In Vue.js v-model directive provides TWO-WAY binding. So in your case "car_name" is same data for input tag and for data(). You can read more about it here v-model click here Other way of handling input value to data its listening event of input, for example:

<input @input="onInput" /> // tag in template

onInput(event){ // handler for event
this.inputValue = event.target.value; // setting your value with input value
}

Under the hood, its same behaviour for v-model and code I wrote. About this, you can read this article click here

tony19
  • 125,647
  • 18
  • 229
  • 307
Alex Monk
  • 116
  • 3