Vue中渲染字符串形式组件标签并绑定事件
封装子组件
<template
>
<div
>
<!-- :html 给子类传参 @handleChange 让子类可调用父类方法
-->
<cmp
:html
="data" @handleChange
="handleChange"></cmp
>
</div
>
</template
>
<script
>
import Vue
from 'vue';
export default {
name
: "subClass",
data() {
return {
data
:'<el-button type="primary" size="mini">点击事件</el-button>',
};
},
methods
: {
handleChange(){
this.$emit(this.function);
},
},
props
:['function'],
components
: {
cmp
: {
props
: {
html
: String
,
},
render(h
) {
const com
= Vue
.extend({
template
: this.html
,
})
return h(com
,{
nativeOn
: {
click
:()=>{
this.$emit("handleChange")
}
},
})
}
}
},
}
</script
>
<style scoped
>
</style
>
父组件调用子组件
<template
>
<div
>
<subClass
:function="'testClick'" @testClick
="testClick"></subClass
>
</div
>
</template
>
<script
>
import subClass
from '@/components/subClass'
export default {
name
: "parentClass",
data() {
return {
};
},
methods
: {
testClick(){
console
.log("Vue中渲染字符串形式组件标签并绑定事件");
}
},
components
:{subClass
}
}
</script
>
<style scoped
>
</style
>
效果图:
转载请注明原文地址: https://lol.8miu.com/read-16761.html