Vue.js 将Vue单击事件添加到通过API获取的HTML字符串

Vue.js 将Vue单击事件添加到通过API获取的HTML字符串,vue.js,electron,Vue.js,Electron,我有一些通过API获得的HTML字符串。假设它看起来像: const msg = 'Lorem ipsum dolor sit <a href="www.google.com">google</a> consectetur adipiscing elit <a href="www.yahoo.com">yahoo</a> lorem ipsum.' const msg='Lorem ipsum

我有一些通过API获得的HTML字符串。假设它看起来像:

const msg = 'Lorem ipsum dolor sit <a href="www.google.com">google</a>
             consectetur adipiscing elit <a href="www.yahoo.com">yahoo</a>
             lorem ipsum.'
const msg='Lorem ipsum dolor sit
献祭精英
洛雷姆·伊普苏姆。”
现在我需要在这些元素上添加Vues@click事件。是否可以解析字符串并在其上添加Vue事件并输出它


基本上,我有一个electron应用程序,我想在链接上添加一些附加逻辑,然后重定向。

检查小提琴后编辑:

将ref附加到字符串似乎不起作用,因此,您应该将
ref
添加到父级,如下所示:

<div id="app">
   <div v-html="msg" ref="msg">
   </div>
</div>
new Vue({
  el: "#app",
  data: {
            msg: 'Lorem ipsum dolor sit <a href="www.google.com">google</a> consectetur adipiscing elit <a href="www.yahoo.com">yahoo</a> lorem ipsum.'
  },
  mounted() {
      this.$refs.msg.children[0].onclick = function(e) {
        e.preventDefault();
        alert('foo')
      };

      this.$refs.msg.children[1].onclick = function(e) {
        e.preventDefault();
        alert('bar')
      };
  }
})

然后将事件添加到其两个子事件中,如下所示:

<div id="app">
   <div v-html="msg" ref="msg">
   </div>
</div>
new Vue({
  el: "#app",
  data: {
            msg: 'Lorem ipsum dolor sit <a href="www.google.com">google</a> consectetur adipiscing elit <a href="www.yahoo.com">yahoo</a> lorem ipsum.'
  },
  mounted() {
      this.$refs.msg.children[0].onclick = function(e) {
        e.preventDefault();
        alert('foo')
      };

      this.$refs.msg.children[1].onclick = function(e) {
        e.preventDefault();
        alert('bar')
      };
  }
})
newvue({
el:“应用程序”,
数据:{
msg:“Lorem ipsum dolor坐在这里与精英们告别。”
},
安装的(){
这是。$refs.msg.children[0]。onclick=function(e){
e、 预防默认值();
警报('foo')
};
this.$refs.msg.children[1].onclick=function(e){
e、 预防默认值();
警报('bar')
};
}
})

此处不需要使用v-html。您可以使用
节点html解析器
轻松解析字符串。然后您可以使用
v-for
来显示html

代码:


a标签在下面
显示标签
从“/components/HelloWorld”导入HelloWorld;
从“节点html解析器”导入{parse};
常量味精=
“Lorem ipsum dolor坐在这里与精英们告别。”;
const tags=parse(msg);
导出默认值{
名称:“应用程序”,
组成部分:{
你好世界
},
安装的(){
控制台日志(标签);
},
数据(){
返回{
a_tags:[tags.childNodes[1],tags.childNodes[3]]
};
},
方法:{
showTags(){
console.log(this.a_标记);
}
}
};
#应用程序{
字体系列:“Avenir”,Helvetica,Arial,无衬线;
-webkit字体平滑:抗锯齿;
-moz osx字体平滑:灰度;
文本对齐:居中;
颜色:#2c3e50;
边缘顶部:60像素;
}

我假设html字符串不仅包含a标记,对吗?如果没有,我唯一的建议是将它解析为一个标记,并在字符串中添加一个表示您想要做什么的字符串。@t太平洋,它只是带有
a
HTML元素的文本。我尝试了你的建议,但我无法通过
v-html
添加解析内容,因为@click不起作用。似乎不起作用。无法读取未定义的属性“$el”-很抱歉响应太晚-效果很好。谢谢