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

Vue 3 列表无法更新咨询:API取数后模板不渲染

问题原因及解决方法

你遇到的问题核心是:list是普通JS数组,不是Vue的响应式变量,所以直接赋值后模板无法追踪到变化,自然不会更新。

Vue3里要让数据驱动模板更新,必须使用响应式API创建变量,下面给两种可行的解决办法:

方法一:使用ref(推荐处理数组/基本类型)

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

// 用ref创建响应式数组,初始值为空
const list = ref([]);

function init() {
    axios
        .post("/some-link/here")
        .then((o) => {
            // ref变量要通过.value赋值
            list.value = o.data.bla;
            console.log(list.value);
        })
        .catch((err) => {
            // 可以在这里添加错误处理,比如打印错误信息
            console.error('请求失败:', err);
        });
}

onMounted(() => {
    init();
});
</script>

<template>
  <p v-for="(val, index) in list" :key="index">
     {{ val.name }}
  </p>
</template>

方法二:使用reactive(适合处理复杂对象)

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

// 用reactive包裹一个包含list的对象
const state = reactive({
  list: []
});

function init() {
    axios
        .post("/some-link/here")
        .then((o) => {
            // 直接更新state里的list属性
            state.list = o.data.bla;
            console.log(state.list);
        })
        .catch((err) => {
            console.error('请求失败:', err);
        });
}

onMounted(() => {
    init();
});
</script>

<template>
  <p v-for="(val, index) in state.list" :key="index">
     {{ val.name }}
  </p>
</template>

补充说明

Vue3的响应式基于Proxy实现,只有通过ref/reactive创建的变量才会被Vue代理,当它们的值变化时,模板才会自动重新渲染。如果用普通let定义变量,哪怕赋值了新数据,Vue也不会监测到这个变化,所以模板不会更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:20:20