使用v-html中渲染富文本内容,绑定点击事件
- 使用事件代理,把点击事件绑定到父元素上
@click='cb(event)'
,然后在cb函数中判断触发事件的元素。
div(v-html="content" @click="cb($event)")
cb(e){
if (e.target.nodeName === 'A') {
var url = e.target.getAttribute('href')
console.log(url)
if (!/http:\/\/|https:\/\//.test(url)) {
url = 'http://' + url
}
window.open(url)
}
}
使用Compontent模版编译html内容
- 背景:后端返前端html格式的数据,前端用v-html解析渲染,如:<a @click="show(1)">,a标签能成功渲染,但其绑定的事件无法触发。
- 原因:vue没有将其作为vue的模板解析渲染
- 解决方案:不用v-html而是component模板编译
<template lang="pug">
.hello
h1 我是父组件
.parent(id="parent")
</template>
<script>
import Vue from 'vue';
var MyComponent = Vue.extend({
template: '<a @click="show(1)">点击测试</a>',
methods: {
show(i) {
console.log(i);
},
}
});
var component = new MyComponent().$mount();
export default {
data() {
return {}
},
methods: {
},
mounted() {
document.getElementById('parent').appendChild(component.$el);
}
}
</script>
参考文档