8 뷰 리서치

source: categories/study/vue-research/vue-research_8.md

8. Write Reusable Code with toREFS in Vue3

  • composables
  • maintain reactivity when exporting composables


ref({
    name: string,
    count: number,
})




{
    name: ref(string),
    count: ref(number),
}



npm init vite

  • ref vs. reactive
    • 영상 링크
    • when working in vue 3 and the composition api 2 different ways create reactive data
      1. ref
      2. reactive
        • a common misconception
          • ref = primitives
          • reactive = objects
          • primitives(boolean, string, number, etc) must use ref
          • but reactive objects can use ref or reactive


<script setup>
import {ref, reactive} from "vue";

// string, number, object, any value
const msg = ref("hello world");

// print out message
console.log(msg.value); // we don't need .value in our template, though

// change msg
msg.value = "new value"; // ref calls reactive with a single property, and return proxy
                         // proxys detect changes and create vue's reactivity
                         // we can access a proxy w/state.count (no.value!) butn state is not just { count }

const state = reactive({
    msg: msg, // link to msg ref
})

state.msg = "changed";

console.log(msg.value); // => changed
</script>

<template>
    MSG REF: {{ msg }}
</template>    


  • reactive objects can be made with ref or reactive


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

const reactiveState = reactive({
    msg: 'hello world',
});

console.log(reactiveState);

const refState = ref({
    msg: 'hello world',
});

console.log(refState.value);
</script>




const readonlyState = readonly(reactiveState);




const readonlyState = readonly(refState.value);




const { msg } = toRefs(readonlyState);
console.log(msg.value);




const { msg } = toRefs(refState.value);
console.log(msg.value);


  • Basically: refState.value = reactiveState
  • So which should i use?
  • disclaimer!!
    • i use ref 100% of the time!!
    • but what about .value!
    • i like needing .value
    • .value means reactive


const state = reactive({
  msg: 'hello'
})

// state might just be a plain JS object
state.msg = 'hello';




const state = ref({
  msg: 'hello'
})

// state is a ref! reactive!!
state.value.msg = 'hello'