I'm currently delving into Vue.js and stumbled upon an unusual behavior that I couldn't find any information about on the Internet.
For some reason, the DIV with v-else isn't rendering any content that I place inside it.
I tried to understand why this is happening and all I could find was a suggestion not to use v-for and v-if on the same element (which I don't think I'm doing).
When I remove v-else, everything works perfectly. Below is an example of my code (I believe it's quite self-explanatory, but if not, please let me know and I can provide more details). Thank you in advance for any help!
<template>
<div v-if="error">{{ error }}</div>
<div v-if="post" class="post">
<h3>{{ post.title }}</h3>
<span v-for="tag in post.tags" :key="tag"> #{{ tag }} </span>
<p class="pre">{{ post.body }}</p>
</div>
<div v-else>
<Spinner />
</div>
</template>
<script>
import Spinner from "../components/Spinner.vue";
import getPost from "../composables/getPost";
export default {
props: ["id"],
components: { Spinner },
setup(props) {
const { post, error, load } = getPost(props.id);
load();
return { post, error };
},
};
</script>
<style>
.post {
max-width: 1200px;
margin: 0 auto;
}
.post p {
color: #444;
line-height: 1.5em;
margin-top: 40px;
}
.pre {
white-space: pre-wrap;
}
</style>
As requested, here is my getPost method:
import { ref } from "vue";
const getPost = (id) => {
const post = ref({});
const error = ref(null);
const load = async () => {
try {
// simulate delay
await new Promise((resolve) => setTimeout(resolve, 1000));
let data = await fetch("http://localhost:3000/posts/" + id);
if (!data.ok) throw Error("Sorry, no data available");
post.value = await data.json();
} catch (err) {
error.value = err.message;
}
};
return { post, error, load };
};
export default getPost;
And this is how it appears in json-server:
{
"posts": [
{
"id": 1,
"title": "Welcome to my blog",
"body": "Dolor proident consectetur veniam magna Lorem enim laboris cupidatat dolor do commodo officia veniam occaecat. Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
"tags": ["webdev", "coding", "news"]
},
{
"id": 2,
"title": "Top 5 CSS tips",
"body": "Et incididunt in pariatur commodo fugiat elit eiusmod proident duis proident magna laborum occaecat minim. Ex eu sint cillum proident ea Lorem nulla consequat incididunt tempor reprehenderit laborum sit. Enim nulla sint sunt nulla deserunt officia occaecat sunt velit qui in aliquip. Non nulla et mollit esse ad qui mollit id.",
"tags": ["webdev", "coding", "css"]
}
]
}