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