南康做网站,深圳seo优化公司排名,关于网站建设与维护的心得体会,在家用服务器做网站目录 定义语法使用场景场景一场景二场景三tips只有一个默认插槽时 定义
在Vue中#xff0c; v-slot 指令用于定义插槽的模板内容。它用于在父组件中传递内容到子组件中的插槽。 v-slot 指令可以用于 标签或组件标签上#xff0c;以便在子组件中使用插槽。
语法
使用 v-slo… 目录 定义语法使用场景场景一场景二场景三tips只有一个默认插槽时 定义
在Vue中 v-slot 指令用于定义插槽的模板内容。它用于在父组件中传递内容到子组件中的插槽。 v-slot 指令可以用于 标签或组件标签上以便在子组件中使用插槽。
语法
使用 v-slot 指令时可以使用以下两种语法
缩写语法 # 符号表示 v-slot 指令后面跟插槽名称。
template #插槽名称!-- 插槽内容 --
/template完整语法 v-slot 指令后面跟着 : 后面是插槽名称。
template v-slot:插槽名称!-- 插槽内容 --
/template使用场景
v-slot 指令的使用场景包括但不限于以下几种
在组件中使用插槽将父组件中的内容传递给子组件。在子组件中使用具名插槽根据插槽名称渲染不同的内容。在子组件中使用作用域插槽将子组件中的数据传递到父组件中进行渲染。
场景一
在组件中使用插槽将父组件中的内容传递给子组件。
父组件
templatedivchild-componenttemplate v-slot:default!-- 插槽内容 --pThis is the content passed from the parent component./p/template/child-component/div
/template子组件
templatedivslot/slot/div
/template场景二
在子组件中使用具名插槽根据插槽名称渲染不同的内容
父组件
templatedivchild-componenttemplate v-slot:header!-- 插槽内容 --h1Header Content/h1/templatetemplate v-slot:body!-- 插槽内容 --pBody Content/p/template/child-component/div
/template子组件
templatedivslot nameheader/slotslot namebody/slot/div
/template场景三
在子组件中使用作用域插槽将子组件中的数据传递到父组件中进行渲染
父组件
templatedivchild-componenttemplate v-slot:defaultslotProps!-- 插槽内容 --p{{ slotProps.message }}/p/template/child-component/div
/template子组件
templatedivslot :messagemessage/slot/div
/templatescript
export default {data() {return {message: Hello from child component!};}
};
/script在router-view中的应用拿到router-view中的Component值同时利用component 标签动态渲染组件 router-view v-slot{ Component, route }transition appear namefade-transform modeout-inkeep-alive :includekeepAliveNamecomponent :isComponent v-ifisRouterShow :keyroute.fullPath //keep-alive/transition/router-viewtips
如果父组件没有向插槽传入值则子组件会显示原来的内容当传入具体的值时则会覆盖掉插槽内的内容
子组件
templateslot namea1 :contentslot_data h1child-123/h1 /slot
/templatescript langts setup
const slot_data child-content;
/scriptstyle scoped/style父组件
templatedivh5slot-test/h5child!-- template #a1{ content }div{{ content }}/div/template --/child/div
/templatescript langts setup
import child from ./child.vue;
/scriptstyle scoped/style此时注释掉插值代码结果如图只会显示原来槽内内容
父组件代码修改如下
templatedivh5slot-test/h5childtemplate #a1{ content }div{{ content }} 我是父组件/div/template/child/div
/templatescript langts setup
import child from ./child.vue;
/scriptstyle scoped/style显示内容如图所示则会覆盖掉原来槽值
在v-slot中既可以由子组件向父组件传值slot_data又可以由父组件向子组件传递html内容可以看做是‘’双向的‘’ 在一些场景比如子组件渲染的内容既需要子组件数据又需要父组件数据时可以考虑使用插槽来完成
props同样也可以向子组件传值在子组件中同一渲染完成这是之前一直使用的方式之后可以考虑使用插槽拿到子组件中的值又可以向子组件传递内容
只有一个默认插槽时
可以直接这样写类似于上述router-view的用法 子组件
templateslot :contentslot_data :content2slot_data2 /slot
/templatescript langts setup
const slot_data child-content;
const slot_data2 child-content2;
/script父组件 contentcontent2采用解构赋值直接从slotProps值默认传递变量的名称中得到templete也可以省略child标签内的所有值都会被传入插槽
templatedivh5slot-test/h5child v-slot{ content, content2 }!-- h1{{ content }}/h1 --{{ content }}{{ content2 }}784561/child/div
/templatescript langts setup
import child from ./child.vue;
/script结果如图