[Vuejs]-Vuejs3 + Axios + Express – Display data from array/object

1👍

Since your API is returning an array with one post, you can just store the post without the array around it.

<template>
<div v-if="post">
    <h2>{{ post.title }}</h2>
    <p>{{ post.body }}</p>
</div>
</template>

<script>
import axios from 'axios'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export default {
    name: 'BlogPostView',
    setup() {
        const post = ref({}) // make this an object
        const route = useRoute()
        const error = ref('')

        const load = async (id) => {
            
            try {
                const response = await axios.get(`http://localhost:5000/api/posts/${id}`)
                post.value = response.data[0] // Get the first item from the array
                console.log(post.value)
                console.log(response.data) 
            } catch(err) {
                error.value = err.message
            }            
        }

        load(route.params.id)

        return { post, error }
    }
}
</script>

👤Turtle

Leave a comment