skip to Main Content

I’m playing around with Vue, and I’ve seen you can set up a ‘watch’ callback for when a piece of Data changes:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input v-model="inputVal" placeholder="edit me" />
    <p>{{ inputVal }}</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      inputVal: '22'
    }
  },

  watch: {
    inputVal: function(val, oldVal) {
      console.log('inputVal changed');
      console.log(oldVal);
      console.log(val);
    }
  }
}
</script>

If I want to make a change to the data state inside the watch.inputVal function, how would I do that?

2

Answers


  1. It’s pretty simple:

    data() {
      return {
        inputVal: '22',
        isValueOdd: false
      }
    },
    
    watch: {
      inputVal(val, oldVal) {
        this.isValueOdd = val % 2 !== 0
      }
    }
    

    But generally if some of your state is dependent on some other state, it might be a better idea to use computed instead of watch:

    data() {
      return {
        inputVal: '22'
      }
    },
    
    computed: {
      isValueOdd() {
        return this.inputVal % 2 !== 0
      }
    }
    

    Computed is lazy, cached and overall easier to understand. The main purpose of watch is to execute side effects.

    Login or Signup to reply.
  2. Inside the watch you can access data object using this keyword. To make changes to data object you can update using this.propertyName = newValue.

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <input v-model="inputVal" placeholder="edit me" />
        <p>{{ inputVal }}</p>
        <p>{{ anotherState }}</p>
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      props: {
        msg: String,
      },
      data() {
        return {
          inputVal: '22',
          anotherState: 'Waiting for input',
        };
      },
    
      watch: {
        inputVal: function (val, oldVal) {
          console.log('inputVal changed');
          console.log(oldVal);
          console.log(val);
          this.anotherState = val + ' entered';
        },
      },
    };
    </script>
    

    In this code we have new data state named anotherState, it gets updated whenever inputVal is changed. I am not sure if I got your question correctly. Is that something you were looking for?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search