Vue更新模板Ref时出现Cannot find module './undefined'错误排查
Vue动态更新ref渲染组件异常问题排查与解决
需求目标
基于动态变化的reference(ref)渲染组件,用户可执行“搜索”功能获取数据并更新ref,更新后的ref需自动更新通过v-for渲染的组件。
环境配置
在onMounted()生命周期钩子中通过axios请求获取所有数据并存入ref:
onMounted(async () => { const response = await axios.get('/api/subject/') allSubjects.value = await response.data.data; })
对应的ref定义:
const allSubjects = ref(null)
模板部分:
<OneSubject v-for="subject in allSubjects" :key="subject.id" :subject="subject" />
目前这部分功能正常运行。
问题描述
执行搜索功能时,axios请求可正常获取响应数据(新的对象数组),但更新ref时出现错误:
async function search(searchInput) { const response = await axios.get(`/api/subject/search/${searchInput}`) console.log(response) // <-- 响应包含数据 allSubjects.value = await response.data.data; // <-- 触发错误 }
错误来自v-for渲染的OneSubject组件,报错信息为Cannot find module './undefined'。可确认ref已成功更新为新数据,但渲染组件时出现异常。
问题排查
OneSubject组件初始代码如下:
<template> <div class="subject-wrapper" v-bind:style="{ background: `rgba(0, 0, 0, .3) url('${imgSrc}') center / cover` }"> <div class="darken-bg"></div> <div class="subject-name">{{ subject.name }}</div> </div> </template> <script setup> import { onMounted, computed } from 'vue' const props = defineProps({ subject: Object }) const imgSrc = computed(() => require(`@/assets/images/subject/${props.subject.image}`)) </script>
修改组件代码为:
<template> <div class="subject-wrapper" v-bind:style="{ background: `rgba(0, 0, 0, .3) url('${imgSrc}') center / cover` }"> <div class="darken-bg"></div> <div class="subject-name">{{ subject.name }}</div> </div> </template> <script setup> import { reactive, computed, onUpdated } from 'vue' const props = defineProps({ subject: Object }) const subject = reactive(props.subject) const imgSrc = computed(() => require(`@/assets/images/subject/${subject.image}`)) onUpdated(() => { console.log('component subject prop:', props.subject) console.log('subject reactive:', subject) }) </script>
修改后搜索无报错,但渲染了错误的组件,控制台日志显示组件props仅包含2个字段。
解决方案
最终发现错误源于服务端响应数据缺失image字段,组件渲染时require该字段对应的图片资源,因字段不存在导致路径变为./undefined,触发模块找不到的错误。调整接口返回完整的文档属性后问题解决。
内容的提问来源于stack exchange,提问作者Jeremy Kung
相关产品推荐
相关产品推荐

