前言
今天逛掘金的时候,看到了一篇文章Vue 如何跨组件传递 Slot
思索
众所周知,Vue
中组件传递一般都是使用插槽,但是在一些需要跨 N 层父子关系的情况下,就非常的难受
回过头来看看React
就可以直接通过props
来传递组件,简单粗暴
function SplitPane(props) {
return (
<div className="SplitPane">
<div className="SplitPane-left">{props.left}</div>
<div className="SplitPane-right">{props.right}</div>
</div>
);
}
function App() {
return <SplitPane left={<Contacts />} right={<Chat />} />;
}
虽然大数情况Vue
的slot
更胜一筹,但是那么Vue
中可不可以使用React
这种写法呢?
答案是当然可以啦 ,那就是component
组件和is
属性
介绍
component
渲染一个“元组件”为动态组件。依 is 的值,来决定哪个组件被渲染
其中 is
类型为string | ComponentDefinition | ComponentConstructor
所以我们只要使用
<template lang="pug">
div
component(:is="Component1")
component(:is="Component2")
</template>
<script>
import Component1 from "./Component1.vue"; //组件1
import Component2 from "./Component2.vue"; //组件2
export default {
data() {
return { Component1, Component2 };
},
};
</script>
他们就能直接在实例中正常渲染了;
由此,我们举一反三,就能通过prop
provide / inject
或者通过其他方式将组件传递到子组件
// 父 template
Child(:my-slot="Component2")
// 子
<template lang="pug">
component(:is="mySlot")
</template>
<script>
export default {
props: ["mySlot"],
};
</script>
emmm,有react内味了...
结语
完了完了,又到了猝死的时间了