FE/Vue.js

[Vue.js 3] Computed, async / await, watchEffect, watch

멍목 2023. 7. 16. 19:56
반응형

프로젝트로 배우는 Vue.js 3

이 포스팅에서 작성하는 내용은 프로젝트로 배우는 Vue.js 3 에서 발췌하였습니다.

 

https://inf.run/sxQT

 

프로젝트로 배우는 Vue.js 3 - 인프런 | 강의

Vue.js 3 사용 방법을 배우고 프로젝트에 적용을 하면서 익힐 수 있도록 도와드립니다., - 강의 소개 | 인프런

www.inflearn.com


Computed

  • Computed로 변수를 정의하면, 내부에 사용된 state 변수(reactive, ref) 의 상태가 변할 때 자동으로 영향을 받음
  • Computed 로 정의된 변수를 재호출 시, 이전에 계산된 값을 호출하지만
    아래 예제와 같은 Method를 재호출 시, 다시 해당 Method의 로직을 계산 후 호출됨
<template>
  <p> str: {{ str }} </p>
  <p> helloStrComputed: {{ helloStrComputed }} </p>
  <p> helloStrMethod: {{ helloStrMethod }} </p>
  <buttom @click="changeStr">change</button>
</template>

<script>
import { ref, computed } from 'vue';

export default {
  setup() {
    let str = ref('IronMan');
    
    let helloStrComputed = computed(() => {
      return hello + str.value;
    });
    
    let helloStrMethod = () => {
      return hello + str.value;
    });
    
    return {
      str,
      helloStrComputed,
      helloStrMethod,
    };
  }
}
</script>

 

 

 

async / await

  • 특정 Method 가 동기 방식으로 흘러가길 원할 때 사용하는 기능
  • 함수를 async로 감싸준 후에 통신하는 부분에 await를 넣어서 표시.
  • try ~ catch로 성공 및 실패를 설정
<script>
const insertData = async (data) => {
  try {
    const res = await axios.post('http://localhost:8080/todos', {
      data: data
    });
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}
</script>

 

 

 

watchEffect

  • watchEffect 내부에 정의한 state 변수(reactive, ref) 의 값이 변경될 때마다 작동
  • state 변수 변경 감지
<template>
  {{ str }} 
  <button @click="btnClicked">Button</button>
</template>

<script>
import { ref, watchEffect } from 'vue';

export default {
  setup() {
    let str = ref('IronMan');
    
    watchEffect(() => {
      // str 이 변경될 때마다 console 출력
      console.log('str value : ' + str.value);
    });
    
    const btnClicked = () => {
      str.value = 'SpiderMan';
    };
    
    return {
      str,
      btnClicked,
    };
  }
}
</script>

 

 

watch

  • watchEffect와 마찬가지로, 내부에 정의한 state 변수(reactive, ref) 의 값이 변경될 때마다 작동
  • watch 는 변경되기 전 값을 가지고 있음
  • reactive 변수와 사용 방법이 미세하게 다름
<template>
  {{ str }} 
  <button @click="btnClicked">Button</button>
</template>

<script>
import { ref, reactive, watchEffect } from 'vue';

export default {
  setup() {
    // ref
    let str = ref('IronMan');
    
    watch(str, (current, prev) => {
      // str 변경될 때마다 console 출력
      console.log('변경 전: ' + prev);
      console.log('변경 후: ' + current);
    });
    
    const btnClicked = () => {
      str.value = 'SpiderMan';
    };
    
    // reactive
    let str2 = reactive({
      name: 'tom',
      age: 18
    });
    watch(() => [str2.name, str2.age], (current, prev) => {
      // str2 변경될 때마다 console 출력
      console.log('변경 전: ' + prev);
      console.log('변경 후: ' + current);
    });
    
    return {
      str,
      btnClicked,
    };
  }
}
</script>

 

반응형