房建设计网站,做行业网站广告能赚多少钱,易风网站建设,白酒 网站模板Vue3 插槽 使用笔记
介绍
在 Vue 3 中#xff0c;插槽#xff08;Slot#xff09;是一个非常强大的特性#xff0c;它允许我们更好地组织和重用组件。通过定义插槽#xff0c;子组件可以预留出由父组件控制的区域#xff0c;这样父组件就可以向这些区域填充自己的内容。…Vue3 插槽 使用笔记
介绍
在 Vue 3 中插槽Slot是一个非常强大的特性它允许我们更好地组织和重用组件。通过定义插槽子组件可以预留出由父组件控制的区域这样父组件就可以向这些区域填充自己的内容。这增加了组件的灵活性和可复用性。
Vue 3 中插槽的种类
在 Vue 3 中插槽主要分为以下几种类型
默认插槽Default Slot
默认插槽是最基本的插槽形式如果没有特别指定插槽名称则所有内容都会被放置在这个插槽中。
示例
!-- 子组件 --
templatedivslot默认内容/slot/div
/template!-- 父组件 --
templateChildComponent!-- 默认插槽的内容 --p这是从父组件传入的内容。/p/ChildComponent
/template具名插槽Named Slot
具名插槽允许我们在子组件中定义多个插槽并给每个插槽指定一个名称。
示例
!-- 子组件 --
templatedivheaderslot nameheader默认头部内容/slot/headermainslot默认主体内容/slot/mainfooterslot namefooter默认页脚内容/slot/footer/div
/template!-- 父组件 --
templateChildComponenttemplate v-slot:headerh1这是头部/h1/templatep这是主体内容。/ptemplate v-slot:footerp这是页脚/p/template/ChildComponent
/template作用域插槽Scoped Slot
作用域插槽允许父组件访问子组件的数据。子组件可以通过 v-slot 指令传递数据给父组件。
示例
!-- 子组件 --
templateslot :itemitemspan{{ item.name }}/span/slot
/template
script
export default {data() {return {item: { name: 示例名称 }};}
};
/script!-- 父组件 --
templateChildComponent v-slot:item{ item }p{{ item.name }}/p/ChildComponent
/template使用技巧
1. 简化具名插槽
在 Vue 3 中你可以使用 template 标签来简化具名插槽的写法
!-- 父组件 --
templateChildComponenttemplate #headerh1这是头部/h1/templatep这是主体内容。/ptemplate #footerp这是页脚/p/template/ChildComponent
/template2. 动态具名插槽
插槽名称可以是动态的这意味着你可以使用表达式来指定插槽的名称
!-- 父组件 --
templateChildComponenttemplate v-slot:[dynamicSlotName]p动态插槽内容/p/template/ChildComponent
/template
script
export default {data() {return {dynamicSlotName: header};}
};
/script3. 插槽绑定事件
虽然 slot 标签本身不能直接绑定事件但通常的做法是在外部包裹一层元素然后把事件绑定到这个元素上
!-- 父组件 --
templateChildComponenttemplate v-slot:default{ on }span clickon.click点击我/span/template/ChildComponent
/template4. 插槽默认内容
当没有内容填充到插槽中时可以通过在子组件中为 slot 标签添加默认内容来设置默认值。
总结
插槽是 Vue 3 中一个非常重要的概念它允许我们创建更加灵活和可复用的组件。 无论是默认插槽、具名插槽还是作用域插槽都为我们提供了丰富的手段来构建组件间的互动和内容填充。 通过合理利用插槽我们可以编写出更加模块化且易于维护的 Vue 应用程序。