In my current Vue 2 project, I am working on a small blog. The structure involves having a separate component for the post form, where one of the form inputs is a select field for the post's category. This select field should be populated with categories fetched from the database. Additionally, the component receives a post
object from the parent component, which is also fetched from the database using props: ['post']
.
Below is the code snippet:
// HTML
...
<select class="form-control" v-model="post.category_id">
<option
v-for="cat in categories"
v-bind:value="cat.id">
{{ cat.name }}
</option>
</select>
...
// JS
module.exports = {
props: ['post', 'url'],
name: 'postForm',
created: function() {
this.syncCats()
},
methods: {
syncCats: function() {
this.$http.get("/api/categories")
.then(function(res) {
this.categories = res.data
})
}
},
data: function() {
return {
categories: {}
}
}
}
The issue I am facing is that none of the options in the select field are selected by default, as shown in this image. When I open the select, both categories from the database are visible like in this image.
I aim to have the correct value automatically selected by default (post.category_id == cat.id
). How can this be achieved?
I attempted using
<select ... :v-bind:selected="post.category_id == cat.id">
, but encountered the same issue.
Edit
After some testing, I outputted both post.category_id
and cat.id
in the following manner:
<div class="form-group">
<label>Category</label>
<select class="form-control" v-model="post.category_id">
<option
v-for="cat in categories"
:value="cat.id"
:selected="cat.id == post.category_id">
{{ cat.name }} {{ cat.id }} {{ post.category_id }}
</option>
</select>
</div>
Prior to selecting any option, only the cat.id
appears as seen in this image - post.category_id
does not show up. However, after selecting an option, post.category_id
becomes visible as illustrated in this image. It's important to note that the "1" at the end is only present in the second screenshot, indicating the value of {{ post.category_id }}
.
This suggests that the post data is being loaded after the categories, necessitating a way to reinitialize the select field once the data is loaded. How could this be accomplished? For context, here is the parent component responsible for fetching the post:
<template>
<span id="home">
<postForm :post="post" :url="url"></postForm>
</span>
</template>
<script>
var postForm = require('../forms/post.vue')
module.exports = {
name: 'postEdit',
created: function() {
this.$http.get('api/posts/slug/' + this.$route.params.slug)
.then(function(response) {
if(response.status == 200) {
this.post = response.data
this.url = "/api/posts/slug/" + response.data.slug
}
})
},
data: function() {
return {
post: {},
url: ""
}
},
components: {
postForm
}
}
</script>