1、子组件暴露插槽的写法
<template> <div class="hello"> <h1>子组件</h1> <h1>↓↓↓以下是默认插槽内容↓↓↓</h1> <slot :scope="sexEn1"></slot> <h1>↑↑↑以上是插槽内容↑↑↑</h1> <br /> <div>{{sexEn}}</div> <h1>↓↓↓以下是具名插槽 sex的内容↓↓↓</h1> <slot name="sex" :scope="sexEn2"></slot> <h1>↑↑↑以上是具名插槽 sex的内容↑↑↑</h1> </div> </template> <script> import { reactive, toRefs } from 'vue'; export default { setup(a,b) { console.log(b); const state = reactive({ sexEn1: 'femeal', sexEn2: 'meal', age: 23 }); return { ...toRefs(state) }; }, name: 'AgeAndSex' }; </script> <style scoped> .hello { margin: 20px; color: green; border: 1px solid green; } .pointer { cursor: pointer; } </style>
2、父组件使用插槽的写法
<template> <div class="about"> <AgeAndSex> <template v-slot="obj"> <div class="slot">父组件使用插槽反显sexEn1:{{obj.scope}}为{{filter(obj.scope)}}</div> </template> <template v-slot:sex="obj"> <div class="slot">父组件使用插槽反显sexEn2:{{obj.scope}}为{{filter(obj.scope)}}</div> </template> </AgeAndSex> </div> </template> <script> // eslint-disable-next-line no-unused-vars import { reactive, toRefs } from 'vue'; import AgeAndSex from '@/components/AgeAndSex'; export default { setup() { let filter = e => { console.log(e); switch (e) { case 'meal': return '男'; case 'femeal': return '女'; default: return '保密'; } }; return { filter }; }, filters: {}, components: { AgeAndSex } }; </script> <style scoped> .slot { color: red; } </style>
效果图
3、顺带一提:在vue3中,已经废除了管道符(过滤器)的功能,官方提出使用计算属性的解决方案。如果复用性不高,也可以在setup中写方法,或者写在工具函数里(我个人想法是挂载到window上,然后在setup中的返回值中解构)