You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中使用v-for渲染select下拉选项无显示问题求助

Vue3中v-for渲染select下拉选项不显示的解决方法

核心问题:响应式丢失

你通过ref({})创建了响应式变量categories,但在请求数据后直接用categories = response.data.categories覆盖了整个ref对象——这会破坏Vue的响应式追踪机制,导致模板无法感知数据变化,所以下拉选项不会渲染。

从控制台输出看,categories是键值对结构的对象,Vue的v-for本身支持遍历对象,这部分语法没有问题,无需修改模板。

修复方案

1. 正确更新ref变量的值

修改getCategories函数,通过.value更新ref的内部值,保持响应式:

const getCategories = async () => {
    let response = await axios.get(`/api/get_all_category/`)
    categories.value = response.data.categories // 改用.value赋值
    console.log(categories.value) // 打印时建议查看.value的真实数据
}

2. (可选)完善响应式变量声明

如果selectedCategory需要参与双向绑定,也应该用ref声明:

let selectedCategory = ref(null)

3. (可选)确保组件挂载时数据加载完成

在onMounted中添加await,保证数据请求完成后再渲染模板:

onMounted(async () => {
    await getCategories()
})

修正后的完整脚本代码

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

let categories = ref({})
let selectedCategory = ref(null)

onMounted(async () => {
    await getCategories()
})

const getCategories = async () => {
    let response = await axios.get(`/api/get_all_category/`)
    categories.value = response.data.categories
    console.log(categories.value)
}
</script>

模板部分无需修改,保持你原来的代码即可。

内容的提问来源于stack exchange,提问作者erohtpur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:05:21