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

Vue Axios请求数据控制台有输出但前端页面不显示如何解决

问题根因

接口返回数据能正常打印但页面不渲染,是代码存在三个核心错误:

  • 响应式变量未初始化:Vue 2的响应式系统要求所有绑定到模板的变量,必须提前在data返回的对象中声明。直接通过this.xxx = xxx挂载的未声明属性不具备响应式能力,值变更不会触发视图更新,当前代码中data返回空对象,未定义patientName字段。
  • 模板插值语法错误:模板里的双花括号插值默认指向当前组件实例,不需要额外加this,写{{this.patientName}}会导致取值失败。
  • 请求方法未执行:仅定义了getPatient方法,没有在组件生命周期钩子或用户交互事件中调用该方法,接口请求根本不会发起。
修正代码

模板代码

<b-card class="mt-3" header="Patient Information">
  <p>Name {{ patientName }} </p>
  <br><br>
  <div class="graphtitle">Medical Record</div>
</b-card>

脚本代码

import axios from "axios";

export default {
  data() {
    return {
      // 提前声明响应式变量,设置初始值
      patientName: ''
    }
  },
  mounted() {
    // 组件挂载完成后自动调用接口拉取数据
    this.getPatient()
  },
  methods: {
    getPatient() {
      axios.get('https://xxx/medicalRecord/api/v1/getMedicalRecord?patientID=s3333333c')
        .then(response => {
          this.patientName = response.data.message.patientName;
          console.log(response.data.message);
        })
        .catch(error => alert(error));
    }
  }
}

额外提示:如果后续需要给已有响应式对象新增初始未声明的属性,不要直接赋值,使用this.$set(目标对象, 属性名, 属性值)写法,才能保证新增属性具备响应式,正常触发视图更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:06:30