插槽,名字挺新奇。但不要被他的名字难住。其实就是父组件向子件件传递信息的一种手段。我们可以用这样的方法向子组件传值。
父组件(app.vue)
<template><MyCompoent :transData="{a:reactiveObj.a,breactiveObj.b,c}">
</template><script>import {reactive,ref} from 'vue';//批量定义响应式变量const reactiveObj = reactive(a,b)//单独定义的响应式变量const c = ref('c的值')//其他方式定义的能在标签用的...
</script>
子组件(MyComponent.vue)
<template><el-row><el-col>{{a}}</el-col></el-row>
</template><script>import {defineProps} from 'vue'const prop = defineProps({transData:{type:Object,default:()=>({})}})const {a,b,c}=prop.transData;
</script>
通过这样的方法可以向子组件传值。那么插槽呢,下面详细说一说。这种传值的方式。其实传的不是『值』,而是更多样的信息,如代码片段等。
1. 匿名插槽
匿名插槽是最基础的插槽类型,用于将父组件提供的内容插入到子组件指定的位置。
子组件(MyComponent.vue)
<template><div><h2>组件标题</h2><!-- 定义匿名插槽 --><slot></slot></div>
</template><script setup>
// 这里可以写组件的逻辑代码
</script>
在上述代码中,<slot></slot> 定义了一个匿名插槽,它是父组件内容的插入点。
父组件(App.vue)
<template><div><MyComponent><!-- 插入到匿名插槽的内容 --><p>这是插入到组件内部的内容</p></MyComponent></div>
</template><script setup>
import MyComponent from './components/MyComponent.vue';
</script>
2. 具名插槽
具名插槽允许在一个组件中定义多个插槽,并让父组件可以指定内容插入到哪个插槽中。
子组件(MyComponent.vue)
<template><div><header><!-- 具名插槽:header --><slot name="header"></slot></header><main><!-- 匿名插槽 --><slot></slot></main><footer><!-- 具名插槽:footer --><slot name="footer"></slot></footer></div>
</template><script setup>
// 组件逻辑代码
</script>
这里定义了三个插槽,一个匿名插槽和两个具名插槽(header 和 footer)。
父组件(App.vue)
<template><div><MyComponent><!-- 插入到具名插槽 header 的内容 --><template #header><h1>这是头部内容</h1></template><!-- 插入到匿名插槽的内容 --><p>这是主要内容</p><!-- 插入到具名插槽 footer 的内容 --><template #footer><p>这是底部内容</p></template></MyComponent></div>
</template><script setup>
import MyComponent from './components/MyComponent.vue';
</script>
在父组件中,使用 <template #插槽名> 语法来指定内容要插入到哪个具名插槽中,# 是 v-slot: 的缩写。
3. 作用域插槽
作用域插槽允许父组件在插入内容时访问子组件的数据。
子组件(MyComponent.vue)
<template><div><!-- 作用域插槽,向父组件暴露数据 --><slot :message="message"></slot></div>
</template><script setup>
import { ref } from 'vue';
const message = ref('这是子组件的数据');
</script>
在子组件中,通过 :message="message" 将 message 数据传递给插槽,这样父组件就可以使用这个数据。
父组件(App.vue)
<template><div><MyComponent><!-- 接收子组件传递的数据 --><template #default="{ message }"><p>{{ message }}</p></template></MyComponent></div>
</template><script setup>
import MyComponent from './components/MyComponent.vue';
</script>
在父组件中,使用 <template #default="{ 数据名 }"> 语法来接收子组件传递的数据,#default 用于匿名插槽的作用域插槽。
Vue 3 中 slot 的原理
编译阶段
当 Vue 编译器处理模板时,它会识别出 <slot> 标签,并将其转换为特定的虚拟节点(VNode)。对于具名插槽,会记录插槽的名称;对于作用域插槽,会记录传递的数据。
渲染阶段
在组件渲染时,Vue 会检查父组件是否为子组件的插槽提供了内容。如果提供了内容,就会将这些内容插入到对应的插槽位置。对于作用域插槽,会将子组件传递的数据注入到父组件提供的内容中。d
数据流动
- 匿名插槽和具名插槽:数据流动是单向的,父组件向子组件传递内容,子组件无法直接向父组件传递内容。
- 作用域插槽:数据流动是双向的,子组件可以向父组件传递数据,父组件可以使用这些数据来渲染内容。
通过这种方式,slot 机制使得组件可以灵活地接收和展示父组件提供的内容,提高了组件的复用性和可定制性。