[英]Set default value to option select menu with Vue3
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: categories.value 看起来像这样:
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:我构建了 select 标签:
<div class="my-3">
<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.我可以正确看到所有选项,但未相应设置默认选项。
Try first to define selectedCategory
as reactive with ref
:首先尝试将
selectedCategory
定义为与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 class="my-3"> <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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.