Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
How to access a const inside a function in Vue?

I'm using Laravel/Inertia/Vue3, I get the user object, and then I want to use it inside other function, but its always undefined.

<script setup>
// imports...

const props = defineProps({
    // props...
})

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

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

If I try to access the user object in the HTML vía the handlebars, it works as intended, but I can't use it in the click function. Of course I could assign a const user inside the function with the value usePage().props... but this looks quite ugly, and there must be another way.

Of course, I'm pretty new to Vue.

EDIT #####

I'm refering to this when I say it looks ugly:

<script setup>
// imports...

const props = defineProps({
    // props...
})

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

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

There must be a better and correct way

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda