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

Vue.js如何给外部静态HTML注入带v-on的按钮并重新渲染?

问题:动态添加带Vue指令的HTML后如何让Vue识别并渲染?

我已经用Axios成功拉取了静态HTML文件,并且能正常渲染在页面上。现在想实现这么个功能:用户点击编辑按钮后,遍历这个静态HTML里所有带.editable类的元素,给它们加上editing类,同时追加一个带有v-on指令的按钮,让Vue能识别这个指令,重新渲染内容后,点击按钮能触发浮层弹出。

目前我的代码如下:

模板部分

<template>
 <div>
 <div class="row">
 <div id="kbViewer">
 <b-button class="request-edit" @click="letsEditThisStuff({currentUrl: currentUrl})">Request An Edit</b-button>
 <div v-html="htmlData">
 {{ htmlData }}
 </div>
 </div>
 </div>
 </div>
</template>

脚本部分

data: function () {
 return {
 sampleElement: '<button v-on="click: test()">test from sample element</button>',
 htmlData: '',
 };
},
methods: {
 pullView: function (html) {
 this.axios.get('../someurl/' + html).then(response => {
 let corsHTML = response.data;
 let htmlDoc = (new DOMParser()).parseFromString(corsHTML, "text/html");
 this.rawDog = htmlDoc;
 this.htmlData = htmlDoc.documentElement.getElementsByTagName('body')[0].innerHTML;
 })
 },
 letsEditThisStuff(item) {
 let htmlDoDa = this.htmlData;
 // 这段代码不生效——我想遍历HTML找到所有.editable类的元素,给它们加上editing类
 // 直接操作#document是可以的,但操作htmlData不行
 for (const element of this.htmlData.querySelectorAll('.editable')) {
 element.classList.add('editing');
 // 我想在这里把上面的sampleElement(或者类似的按钮)添加到htmlData里,然后让Vue重新渲染
 let textnode = document.createElement(sampleElement);
 textnode.classList.add('request-the-edit')
 textnode.innerHTML = 'edit me!'
 element.append('<button v-on="click: test()">test from sample element</button>')
 console.log('what is the element?', element)
 }
 this.htmlData = htmlDoDa
 },
}

我知道代码里有些变量没定义,现在只需要解决核心问题:遍历存储的htmlData,找到带.editable类的节点,追加带有v-on指令的按钮,让Vue重新解析并渲染这段HTML。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:51:38