vue 的 jsx 如何动态渲染 component

vue 要在 template 动态调用组件非常简单只需要 <component> 组件配合 is 属性就可以动态渲染组件。

1
2
3
<template>
true<compoment :is='someComponent'></compoment>
</template>

不过在 jsx 中使用 <component> 组件的话会报错,显示该组件不存在无法渲染。因此需要换一个方式。

由于 jsx 本质就是 js 不需要 component 组件做中介,可以通过 js 直接找到对应组件

1
2
3
4
5
6
...
render(){
const Comp = this.someComponent
return (<Comp></Comp>)
}
...

这是由于如果一个变量指向了一个组件,那么这个变量名可以直接被 jsx 解析并渲染。

因此在文档中也会提到到我们可以不将组件加载到父组件当中,直接经由 jsx 渲染出来的原因

1
2
3
4
5
6
import componentA from 'xxx'
...
render(){
return (<componentA></componentA>)
}