I get all the categories:
const getCategories = async () => {
let response = await axios.get(`/api/get_all_category/`)
categories.value = response.data.categories
}
categories.value looks like this:
I set the default option:
let selectedCategory
const getSingleProduct = async () => {
let response = await axios.get(`/api/get_edit_product/${props.id}`)
form.value = response.data.product
//form.value.category_id is a number from 1 to 6
selectedCategory = ref(form.value.category_id)
}
I build the select tag:
<div >
<p>Product type</p>
<select v-model="selectedCategory">
<option v-for="category in categories" :key="category.id" :value="category.id">
{{ category.name }}
</option>
</select>
</div>
I can see all the options correctly but the default option is not set accordingly.
CodePudding user response:
Try first to define selectedCategory
as reactive with ref
:
const { ref, computed } = Vue
const app = Vue.createApp({
setup() {
const categories = ref([{id: 1, name: 'aaa'}, {id: 2, name: 'bbb'}, {id: 3, name: 'ccc'}])
let selectedCategory = ref(null)
const getSingleProduct = () => {
//let response = await axios.get(`/api/get_edit_product/${props.id}`)
// form.value = response.data.product
//form.value.category_id is a number from 1 to 6
selectedCategory.value = 3
}
getSingleProduct()
return { categories, selectedCategory }
},
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div >
<p>Product type</p>
<select v-model="selectedCategory">
<option v-for="category in categories" :key="category.id" :value="category.id" :selected="selectedCategory">
{{ category.name }}
</option>
</select>
</div>
</div>