본문 바로가기
개발이야기/Vue

[Vue] Vue3 ref, reactive 사용해보기

by dev.josh 2020. 9. 20.
반응형

이번에 vue3에서 composition api가 추가됨으로써  

vue2 사용자 시점에서 ref와 reactive에 대하여 간단한 예제 소스를 작성해 보았다.

 

1. data()와 ref()

기존 vue2에서 데이터를 핸들링 할때는 사실 반응형이라는것에 신경쓰지 않고 사용했던거 같다.

  <div id="app">
    <template>
      {{text}}
    </template>
  </div>

  <script>
    data() {
      return {
        text: "Hello"
      }
    },
    mounted() {
      setTimeout(()=> {
        this.text = this.text + " Vue2"
      },2000)
    }
  </script>

 2초 뒤에 text를 변경하는 예제이다. 반응형이라는것이 그냥 당연하다고만 여겨졌었다..

 

<div id="app">
  {{text1}}<br>
  {{text2}}<br>
</div>

<script>
  const {  
    ref
  } = Vue;

  const App = {
    setup() {
      let text1 = "Hello";
      let text2 = ref("Hello");

      setTimeout(() => {
        text1 = text1 + " Vue3"; 
        text2.value = text1 + " Jo!!"; //ref 는 .value로 접근해야된다
      }, 2000);

      return { 
        text1, 
        text2,
      };
    },
  };
</script>

동일한 vue3의 예제이다. 실행해보면 2초뒤에 text1은 변경이 되지 않고,

ref를 사용한 text2는 변경이된것을 확인 할 수 있다.

setTimeout안에서 vue2와는 다르게 this를 사용하지 않으며, ref에 접근하기 위해서는 .value로 접근해야 된다.

 

최종적으로 text1은 반응형으로 적용되지는 않았지만 "Vue3" 라는 문구는 추가되어, text2의 결과 값은

"Hello Vue3 Jo!!!" 가 되는것을 확인 할수 있었다.

 

 

2. ref()와 reactive()

ref와 reactive의 차이점은 

<div id="app">
  {{obj1}}<br>
  {{obj2}}<br>
</div>

<script>
  const {  
    reactive
  } = Vue;

  const App = {
    setup() {
      let obj1 = ref({
        title: "Hello, ref!",
        description: "",
        content: "ref content",
        //wordCount: computed(() => obj.content.length) ref 안에서는 계산속성을 사용할 수 없음
      });
      let obj2 = reactive({
        title: "Hello, reactive!",
        description: "",
        content: "reactive content",
        wordCount: computed(() => obj2.content.length) //reactive 에서는 계산속성 사용가능
      });

      return { 
        obj1,
        obj2,
      };
    },
  };
</script>

ref에서는 계산 속성이 사용 불가능 했으나, reactive에서는 사용이 가능했다.

즉 reactive에서는 다른 함수를 만들어서 사용가능할것으로 보여진다. (좀더 테스트가 필요)

 

 

전체 소스

vue2CNDStart

  <div id="app">
    <template>
      {{text}}
    </template>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          text: "Hello"
        }
      },
      mounted() {
        setTimeout(()=> {
          this.text = this.text + " Vue2"
        },2000)
      }
    })
  </script>
</body>

</html>

 

 

vue3CDNStart

<div id="app">
  {{text1}}<br>
  {{text2}}<br>
  {{obj1}}<br>
  {{obj2}}<br>
</div>

<script src="http://unpkg.com/vue@next"></script>

<script>
  const { 
    createApp, 
    ref,
    reactive,
    computed 
  } = Vue;

  const App = {
    setup() {
      let text1 = "Hello";
      let text2 = ref("Hello");
      let obj1 = ref({
        title: "Hello, ref!",
        description: "",
        content: "ref content",
        //wordCount: computed(() => obj.content.length) ref 안에서는 계산속성을 사용할 수 없음
      });
      let obj2 = reactive({
        title: "Hello, reactive!",
        description: "",
        content: "reactive content",
        wordCount: computed(() => obj2.content.length) //reactive 에서는 계산속성 사용가능
      });

      setTimeout(() => {
        text1 = text1 + " Vue3";
        text2.value = text1 + " Jo!!!"; //ref 는 .value로 접근해야된다
      }, 2000);

      return { 
        text1, 
        text2,
        obj1,
        obj2,
      };
    },
    //template: `<h1>Hello {{ name }}</h1>`,
  };

  createApp(App).mount("#app");
</script>

 

vue2CDNStart.html
0.00MB
vue3CDNStart.html
0.00MB

 

출처

https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/

 

Vue 3 Composition API: Ref vs Reactive

One question I keep hearing over and over is what method should I use to declare reactive data in the Vue 3 Composition API? In this article, I explain what ref() and reactive() are and try to answer that question.

www.danvega.dev

 

반응형

'개발이야기 > Vue' 카테고리의 다른 글

[Vue] 사진첩 게시판  (0) 2022.11.17
[Vue] vue-class-component 형식에서 Mixin 사용하기  (0) 2020.10.13