Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how can I manually unwrap refs in Vue templates


how can I manually unwrap refs in Vue templates


To manually unwrap refs in Vue templates, you can use the `.value` property. Here's how:

javascript
<template>
  <!-- Unwrap ref manually -->
  <div :style="myRef.value.style"></div>
</template>

<script setup>
  import { ref } from 'vue';

  const myRef = ref({
    style: 'color: black'
  });
</script>

In this example, `myRef` is a reactive reference to an object with a `style` property. To access the `style` property in the template, you need to use the `.value` property to unwrap the ref.

Alternatively, you can use the `computed` property to create a computed property that unwraps the ref:

javascript
<template>
  <!-- Unwrap ref using computed property -->
  <div :style="unwrappedStyle"></div>
</template>

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

  const myRef = ref({
    style: 'color: black'
  });

  const unwrappedStyle = computed(() => myRef.value.style);
</script>

In this example, `unwrappedStyle` is a computed property that unwraps the `style` property from `myRef`.

Citations:
[1] https://github.com/vuejs/language-tools/discussions/1186
[2] https://github.com/vuejs/core/issues/803
[3] https://github.com/vuejs/rfcs/issues/533
[4] https://youtrack.jetbrains.com/issue/WEB-50615/Vue-3-Type-Checking-of-Unwrapped-Refs-of-Union-Types-in-Templates-is-broken
[5] https://stackoverflow.com/questions/77539774/i-dont-understand-ref-unwrapping-in-the-template-using-typescript