vue2升级vue3:this.$createElement is not a function—动态组件升级
this.$createElement
vue2 动态组件加载,this.$createElement非常好使!比如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import { Component as tsc } from 'vue-tsx-support' ; import { Component,Prop } from 'vue-property-decorator' ; const chartPanel = ()=> import ( 'line-chart' ) @Component export default class Demo extends tsc<{}> { @Prop({ required: true , type: Object }) readonly panel; chartData render(){ return this .$createElement(chartPanel, { props: { panelModel: this .panel, chartData: Object.freeze( this .chartData), }, }); } } |
了解vue.$createElement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // @returns {VNode} createElement( // {String | Object | Function} // 一个 HTML 标签名、组件选项对象,或者 // resolve 了上述任何一种的一个 async 函数。必填项。 'div' , // {Object} // 一个与模板中属性对应的数据对象。可选。 { // (详情见下一节) }, // {String | Array} // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成, // 也可以使用字符串来生成“文本虚拟节点”。可选。 [ '先写一些文字' , createElement( 'h1' , '一则头条' ), createElement(MyComponent, { props: { someProp: 'foobar' } }) ] ) |
更多推荐阅读:vue.$createElement的使用实例 https://juejin.cn/post/6969505687114088484
那么vue3 怎么弄呢?
看下官方文档:https://vuejs.org/guide/extras/render-function.html#basic-usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import { defineComponent, h } from 'vue' ; import Panel from '@/plugins/charts/pie-charts/components/chart-panel' ; export default defineComponent({ name: 'ChartWrap' , setup() { const vnode = h(Panel, { m: 222 }); return () => ( <div> <div>title< /div > {vnode} < /div > ); }, }); |
但是,如果是异步组件
1 | const asyncPage = () => import ( './Lazy.vue' ) |
this.$createElement还是没有问题的,但是vue3,这个没有法子,但是vue3 有defineAsyncComponent 方案,具体查看下一章:vue2升级vue3:异步组件defineAsyncComponent》
异步组件导出:
1 2 3 4 5 6 7 8 9 | import pieChartJson from './pie-charts/plugin.json' ; import pieChartLogo from './pie-charts/img/logo.svg' ; import pieChart from './pie-charts/index' ; export const ChartSourceBuildIn = { [pieChartJson.type]: pieChart, }; export const ChartSourceImgBuildIn = { [pieChartJson.type]: pieChartLogo, }; |
加载异步组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import { defineComponent, h } from 'vue' ; import { ChartSourceBuildIn } from '@/plugins/charts/index' ; export default defineComponent({ name: 'ChartWrap' , setup() { const chart = ChartSourceBuildIn[ 'pie-charts' ]; const { ChartPanel } = chart; const vnode = h(ChartPanel, { m: 222 }); return { vnode, }; }, render() { return ( <div> <div>title</div> { this .vnode} </div> ); }, }); |
这个和vue2的方案基本保持一致
转载本站文章《vue2升级vue3:this.$createElement is not a function—动态组件升级》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8850.html
标签:
前端
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了