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

Vue.js中调用Axios接口后无法获取v-html绑定元素innerHTML问题求助

问题根因

  1. 语法结构错误:你提供的Vue实例代码存在语法问题,activate方法被写在了methods配置项外部,导致实例初始化异常,因此mounted阶段查询DOM返回null。
  2. 执行时机完全错位:
    • beforeMount生命周期阶段页面还未完成DOM挂载,此时无法正确读取渲染后的DOM内容
    • Axios请求是异步操作,你在mounted钩子中才发起请求,请求返回前reqData始终为null,v-html没有内容可渲染
    • 即使reqData赋值完成,Vue的DOM更新是异步批量执行的,直接同步读取DOM也拿不到最新的渲染结果
  3. 不推荐直接用document.getElementById操作Vue管理的DOM,容易出现选择失效问题,建议用Vue内置的ref属性绑定DOM元素

修复方案

1. 修正HTML模板,添加ref绑定

<div id="vue-app">
   <div ref="sourceText" style="display: none" v-html="reqData"></div>
</div>

2. 修正Vue实例代码,调整执行逻辑

var vueApp = new Vue({
  el: '#vue-app',
  data(){
    return{
      reqData: null,
      line_spliter: '\n', // 注意补充你自己的分割符配置
      line_array: []
    }
  },
  methods:{
    getStory:function () {
      axios
      .get('https://api.coindesk.com/v1/myApi')
      .then((response) => {
        this.reqData = response.data.content
        // 等待Vue完成v-html的DOM渲染后,再执行读取操作
        this.$nextTick(() => {
          this.activate()
        })
      })
      .catch((error) => console.log('error SMS', error));
    },
    activate: function () {
      // 用ref获取DOM,比id选择器更稳定
      const sourceDom = this.$refs.sourceText
      const sourceText = sourceDom.innerHTML
      this.line_array = sourceText.split(this.line_spliter)
      
      // 直接获取内部p元素和内容
      const pList = sourceDom.querySelectorAll('p')
      // 提取所有p标签的文本内容
      const pContentList = Array.from(pList).map(p => p.textContent.trim())
      console.log(pContentList)
    }
  },
  mounted() {
    this.getStory();
  },
})

额外说明

删除beforeMount阶段的activate调用,该阶段没有任何可读取的有效渲染内容,没有执行意义。

内容的提问来源于stack exchange,提问作者Muhammad Masudur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:27:00