Home > Back-end >  How to display object in a variable in Vue 3 script setup
How to display object in a variable in Vue 3 script setup

Time:11-28

I can't display object in Vue 3 script setup. I used ref, reactive and standard variables but all scenarios is unsuccessful.

I want to reflect the response from the getDetail request to the screen. getDetail is fetching this data asynchronously. I run into a problem in every scenario.

ref() usage


<script setup>
let movie = ref([])

const getMovieData = async ()=> {

try {
const data =  await getDetail('movie', route.params.id)
movie.value.push(data)
}
catch (e){
console.log(e)
}

}
getMovieData()
</script>
<template>

<h1>{{movie[0].original_title}}</h1>

</template>

I am able to show data in this usage but I am getting these errors ref() Error


reactive() usage


<script setup>
let movie = reactive({
  data:null
})

const getMovieData = async ()=>{
  try {
    const data =  await getDetail('movie', route.params.id)
    movie.data = data
  }catch (e){
    console.log(e)
  }
}
getMovieData()
</script>

<template>
<h1>{{movie.data.original_title}}</h1>
</template>

In this usage I can show data but I get similar errors reactive()errors


Standart variable usage

<script setup>

let movie

const getMovieData = async ()=>{
  try {
    const data =  await getDetail('movie', route.params.id)
    movie =data
  }catch (e){
    console.log(e)
  }
}
getMovieData()
</script>

<template>
<h1>{{movie.id}}</h1>
</template>

In this usage, the data does not appear on the screen, because the movie object is formed asynchronously.


How do I manage to display this object on the screen in the most correct way without getting an error?

CodePudding user response:

Write a v-if <h1 v-if="movie && movie.length">{{movie[0].id}</h1> So it only renders when data is available.

CodePudding user response:

Template code runs immediately on component creation. In each case, before movie has been asynchronously assigned, your template code is trying to access some non-existent property. optional chaining is arguably the easiest way to prevent these types of errors:

movie[0]?.original_title

Another option is to provide a default value that matches your template usage so it doesn't error out:

let movie = ref([
  {
    original_title: ''
  }
])
  • Related