[Vuejs]-How to access a const inside a function in Vue?

5👍

computed() returns a ref, so your click handler needs to unwrap the value via the ref‘s value prop:

<script setup>
const user = computed(() => usePage().props.value.user);

const click = () => {
  //alert(`${user.name} clicked`); ❌
  alert(`${user.value.name} clicked`); ✅
}
</script>

Alternatively, you can avoid the unwrapping with the Reactivity Transform in <script setup> (i.e., $computed() in this case):

<script setup>
//const user = computed(() => usePage().props.value.user);
const user = $computed(() => usePage().props.value.user);

const click = () => {
  alert(`${user.name} clicked`);
}
</script>
👤tony19

Leave a comment