computed, watch

채윤·2022년 6월 17일
0

Computed

computed 속성은 data의 필드값이 변경사항을 감시하고 반영된다.
사용자가 로그인 여부를 알아야 할 경우 많이 쓰인다.

<template>
  <div>
    <input type="text" v-model="lastName" />
    <input type="text" v-model="firstName" />
    <h1>Hello, {{ fullName }}</h1>
    <h1>Hello, {{ fullName }}</h1>
    <h1>Hello, {{ fullName }}</h1>
    <h1>Hello, {{ fullName }}</h1>
    <h1>Hello, {{ fullName }}</h1>
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      firstName: "재석",
      lastName: "유",
      fullName,
    };
  },
  computed: {
    fullName() {
      //data 필드에 들어가는 것과 같은 효과
      //fullName메소드가 여러번 써놔도 연산은 한번만 호출됨
      //data의 필드값이 변경사항을 감시하고 반영
      return this.lastName + this.firstName;
    },
  },
  setup() {},
  created() {},
  mounted() {},
  unmounted() {},
  methods: {
    getFullName() {
      return this.lastName + this.firstName;
    },
  },
};
</script>

Watch

데이터 필드의 정의된 값만 사용할 수 있다.
데이터의 변경사항을 바로 감시하고 필드에 값을 갱신할 수 있다.
단점은 자원을 많이 소모해서 꼭 필요한 경우에만 사용하는 것이 좋다.

<template>
  <div>
    <input type="text" v-model.number="x1" />
    <input type="text" v-model.number="x2" />
    <!-- <button type="button" @click="plusNumber">계산</button> -->
    <input type="text" v-model="y" />
  </div>
</template>
<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      x1: 0,
      x2: 0,
      y: 0,
    };
  },
  watch: {
    //데이터 필드의 정의된 값만 사용할 수 있다.
    //데이터 변경사항을 바로 감시하고 필드에 값을 갱신할 수 있다.
    //자원을 많이 소모해서 꼭 필요한 경우에만 사용하는 것이 좋다.
    x1() {
      this.y = this.x1 + this.x2;
    },
    x2() {
      this.y = this.x1 + this.x2;
    },
  },
  setup() {},
  created() {},
  mounted() {},
  unmounted() {},
  methods: {
    plusNumber() {
      this.y = this.x1 + this.x2;
    },
  },
};
</script>

Watch vs Computed

  • watch는 데이터 필드 값 그 자체를 변경하는 것이고, computed는 선언된 필드의 값의 변경사항을 감시하면서 데이터를 갱신해주는 역할을 한다.
  • 연산의 목적보다는 선언한 데이터의 변경사항을 감시하고 특정 메소드를 수행하고 싶을 때 쓰인다.
profile
프론트엔드 개발자

0개의 댓글