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

Vue项目挂载contentShow.value[index]时内容空白且页面异常问题

问题分析与解决

核心问题

  1. 模板错误使用ref的.value:Vue模板中ref变量会自动解包,无需手动写.value,直接访问contentShow[index]即可,写contentShow.value[index]会触发对undefined属性的访问。
  2. 数组赋值方式问题:直接给空数组contentShow按索引赋值时,数组不会自动扩展长度,导致部分索引位置实际为undefined,渲染时抛出Cannot read properties of undefined (reading '0')错误。
  3. 异步加载时序问题:页面初始渲染时blogListInfo为空,异步请求完成后更新数组,若contentShow未同步构建完成,会出现索引不匹配的情况。

解决方案

方案一:模板内直接处理内容(推荐)

省去额外维护contentShow数组的步骤,直接在模板中对文章内容做截断处理:

<template>
  <!-- ... 其他代码 ... -->
  <div v-for="(blog,index) in blogListInfo" :key="index">
    <n-card :title="blog.title" size="huge" style="min-width: 80%;">
      {{ blog.content.length > 10 ? blog.content.substring(0,10)+"..." : blog.content }}
      <!-- ... 卡片底部代码 ... -->
    </n-card>
  </div>
  <!-- ... 其他代码 ... -->
</template>

<script setup>
// 删除contentShow相关所有代码
const blogListInfo = ref([]);
onMounted(()=>{
    loadBlogs();
    loadCategories();
});
const loadBlogs = async ()=>{
    let res = await axios.get("/blog/search");
    blogListInfo.value = res.data.data.rows;
}
// ... 其他代码 ...
</script>

方案二:正确构建contentShow数组

如果需要保留contentShow变量,用map方法生成完整数组,同时模板中去掉.value:

<template>
  <!-- ... 其他代码 ... -->
  <div v-for="(blog,index) in blogListInfo" :key="index">
    <n-card :title="blog.title" size="huge" style="min-width: 80%;">
      {{ contentShow[index] }}
      <!-- ... 卡片底部代码 ... -->
    </n-card>
  </div>
  <!-- ... 其他代码 ... -->
</template>

<script setup>
const blogListInfo = ref([]);
const contentShow = ref([]);
onMounted(()=>{
    loadBlogs();
    loadCategories();
});
const loadBlogs = async ()=>{
    let res = await axios.get("/blog/search");
    blogListInfo.value = res.data.data.rows;
    // 用map生成对应长度的contentShow数组
    contentShow.value = blogListInfo.value.map(blog => {
        return blog.content.length > 10 
          ? blog.content.substring(0,10)+"..." 
          : blog.content;
    });
}
// ... 其他代码 ...
</script>

关键注意点

  • 模板中永远不要给ref变量加.value,Vue会自动处理解包逻辑。
  • 处理数组时,优先用map、filter等方法生成新数组,避免直接给空数组按索引赋值,确保数组长度与内容匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 09:40:14