插槽的基本使用和作用域插槽

编程入门 行业动态 更新时间:2024-10-24 20:23:54

<a href=https://www.elefans.com/category/jswz/34/1756281.html style=插槽的基本使用和作用域插槽"/>

插槽的基本使用和作用域插槽

1.编译作用域

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

即父子组件只能使用各自作用域的数据

2.插槽的后备内容(slot中默认配置内容)

可以在slot中提前设置一段内容作为默认值,当父组件提供插槽内容时将会被覆盖

<!--父组件 -->
<pop-cart class="pop-cart" ></pop-cart>
    <!--子组件-->
<slot name="cartPop">这是子组件插槽的默认内容</slot>

以下会被覆盖

      <pop-cart ref="popCart" class="pop-cart" ><template v-slot:cartPop>这是父组件插槽内容</template></pop-cart>

3.vm.$slots  API 的形式获取子组件插槽内容

vm.$slots用来访问被插槽分发的内容。(在父组件中获取子组件的虚拟DOM)

插槽没有命名时:v-slot:default获取所有子组件插槽的实例。如:this.$refs.child.$slots()

插槽有名字时:v-slot:name

<template>
<!-- BlogPost.vue -->
<div><slot name="header"></slot><slot></slot><slot name="footer"></slot></div>
</template>
<blog-post><template v-slot:header><h1>About Me</h1></template><p>Here's some page content, which will be included in vm.$slots.default, because it's not inside a named slot.</p><template v-slot:footer><p>Copyright 2016 Evan You</p></template><p>If I have some content down here, it will also be included in vm.$slots.default.</p>.
</blog-post><script>
import Vue from 'vue'
Vueponent('blog-post', {render: function (createElement) {var header = this.$slots.headervar body   = this.$slots.defaultvar footer = this.$slots.footerreturn createElement('div', [createElement('header', header),createElement('main', body),createElement('footer', footer)])}
})
</script>

4.作用域插槽

作用域插槽能够实现在父组件中获取子组件的数据

当前插槽绑定数据<slot :user="user" name="userCard">

父组件中通过<template v-slot:userCard="user">{{user}}</template>进行获取和使用

  v-slot:default默认插槽

  v-slot:header具名插槽

实际应用场景:

elementUI表格按钮中获取父组件中的数据,再传入按钮中

<!-- 子组件 -->
<span><slot :user="user">{{ user.lastName }}</slot>
</span>
<!-- 父组件中 -->
<current-user><template v-slot:default="slotProps">{{ slotProps.user.firstName }}</template>
</current-user>

更多推荐

插槽的基本使用和作用域插槽

本文发布于:2023-12-06 03:50:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1666353.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:插槽   作用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!