Vue中渲染字符串形式组件标签并绑定事件

it2024-06-27  45

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(){ //调用父类(parentClass)中的方法 this.$emit(this.function); }, }, //父类传参过来的值 在方法中可使用this.function拿到父类传过来对应的值 props:['function'], components: { cmp: { props: { html: String,//拿父类传过来的值 }, render(h) {//生成组件 const com = Vue.extend({ template: this.html, }) return h(com,{ nativeOn: {//绑定点击事件 还可以On:{} 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>

效果图:

最新回复(0)