Home » vue » How to find out the value of an input which already changed

How to find out the value of an input which already changed

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have3 inputs which each of which has a specific value.

<input type="text" id="inputType" v-model="add_sale.type">
<input type="text" id="inputId" v-model="add_sale.id">
<input type="text" dir="auto" v-model="add_sale.name" id="inputName" class="form-control" placeholder="Material" readonly style="background: #fff;">

I change any of the input values like this:

new Vue({
  data() {
    return{
      material:{
        name: "niaz",
        id: 1,
        type: "human"
      },
      add_sale: {}
    }
  },
  mounted() {
    document.getElementById("inputName").value = this.material.name;
    document.getElementById("inputId").value = this.material.id;
    document.getElementById("inputType").value = this.material.type;
  }
})

Now I need to watch the values that changed before.
I want to know if there is any way to find out what is the value of one of the inputs which changed before and change the name input to Alex if the type was human.

Answers:

Dude,

If I understand you correctly.
you are looking for something to track your previous value.
with Vuejs you can do it very easily. and one more important thing. when you are using vue you don’t need to be dependent on vanilla Javascript

so what you are looking for is something is gonna be like this,

new Vue({
  data() {
    return{
      type : null,
      id: null, 
      name: null, 
      add_sale: {}
    }
  },
  watch: {
    type(oldvalue, newvalue) {
        //do whatever you want to do
    },
    id(oldvalue, newvalue) {
        //do whatever you want to do
    },
    name(oldvalue, newvalue) {
        //do whatever you want to do
    },
  },
  mounted() {
     this.type = 'something' //initial the value
     this.id = 1243 //intial value
     this.name = 'name' //initial value
  }
})
<input type="text" id="inputType" v-model="type">
<input type="text" id="inputId" v-model="id">
<input type="text" dir="auto" v-model="name" id="inputName" class="form-control" placeholder="Material" readonly style="background: #fff;">

so you can do it easily with vuejs watch which pretty much work like on change event listener.

and the parameter oldvalue where you will have the previous data, newvalue is the current data you change