Muscardinus

Watch 본문

카테고리 없음

Watch

Muscardinus 2021. 12. 29. 01:31
728x90

watch는 computed와는 다르게 내부에서 비동기 작업 또는 필요 부가적인 작업 실행 등을 할 때 활용 될 수 있다. 또한, 반환을 반드시 할 필요가 없다.

const vm = Vue.createApp({
  data() {
    return {
      firstName: 'John',
      middleName: '',
      lastName: 'Doe',
      url: 'https://google.com',
      raw_url: '<a href="https://google.com" target="_blank">Google</a>',
      age: 20,
    };
  },
  methods: {
    increment() {
      return this.age++;
    },
    decrement() {
      return this.age--;
    },
    updateLastName(msg, event) {
      event.preventDefault();
      console.log(msg);
      this.lastName = event.target.value;
    },
    updateMiddleName(event) {
      this.middleName = event.target.value;
    },
  },
  computed: {
    fullName() {
      return `${this.firstName} ${
        this.middleName
      } ${this.lastName.toUpperCase()}`;
    },
  },
  watch: {
    age(oldVal, newVal) {
      setTimeout(() => {
        this.age = 20;
      }, 3000);
    },
  },
}).mount('#app');

watch에 있는 age는 data에 있는 age를 바라보면서, 어떠한 변화가 있을 때 3초 후 다시 20으로 바꾸겠다는 의미이다.

728x90
Comments