vue的slot学习

最近vue2.6发布,其中更新的就有插槽slot

先来理解一下什么是插槽,看一个简单例子就能理解

父组件
<div class="test">
    <but-tone>hello world</but-tone>
</div>

子组件
 <div class="but-tone">
    <slot></slot>
 </div>

在渲染时<slot><slot>将会被替换成hello world  。slost是不会被渲染的,它是用来接收父组件传过来的内容。插槽内可以包含模板代码,甚至其他组件。

编译作用域:

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。例如这段代码,子组件是获取不到Text的。

<template>
    <div class="test">
        <bot-tone>{{Text}}</bot-tone>
    </div>
</template>
<script>
import bottonefrom './bottone.vue'
export default{
    components:{
        bottone,
    },
    data(){
        return{
            Text:'hello'
        }
    }
}
</script>

后备内容:就是当 <slot></slot>标签中有值时,默认显示该值,当在父组件中使用新值时,将会替换掉子组件的默认值。

具名插槽:有时候一个子组件需要多个插槽,就可以使用具名插槽。比如这个官网的例子

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>


base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

具名插槽的缩写:跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #

作用域插槽:有时让插槽内容能够访问子组件中才有的数据是很有用的。如何访问子组件的数据呢。看这个例子

//子组件
<template>
    <div class="info">
        <slot v-bind:userInfo="userInfo" name='user'>{{ userInfo.sex }}</slot>
    </div>
</template>

<script>
export default {
    name :'info',
    data () {
        return {
            userInfo:{
                name : 'Tony',
                sex:   'girl',
            }
        }
    }
}
</script>

//父组件
 <user-info>
   <template v-slot:user="infoData">
        {{infoData.userInfo.name}}
    </template>
 </user-info>

这样,父组件就可以拿到子组件中的值。而且infoDate是一个该子组件传过来的值的集合,也就是说可以传多个数据。

官网地址:https://cn.vuejs.org/v2/guide/components-slots.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值