vue 2.6+作用域插槽使用

17 篇文章 0 订阅

v-slot

vue 在 2.6.0 中,具名插槽和作用域插槽引入了一个新的统一的语法 :v-slot 指令。
它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍有用的特性。
但是将会在vue 3 中,这两个指令将会被废弃

vue 2.6.0之后 v-slot只能用在 template上,用在 div 或 p 这种标签上是会报错的

子组建

<template>
  <div class="my-card">
  	  <!-- 把数据传给父组件,接收作用域插槽 !:user=user :text=text 传给外面用-->
      <slot name="scope_slot" :user=user :text=text></slot>
      
	  <!-- 接收具名插槽 !-->
      <slot name="named_slot"></slot>
	
	  <!-- 接收默认匿名插槽 !-->
      <slot></slot>
  </div>
</template>

<script>
export default {
    name:'card',
    data(){
        return{
            user:[
                {
                    name:'jenson',
                    age:'21'
                },
                {
                    name:'wjh',
                    age:'20'
                }
            ],
            text:{
                msg:'作用域插槽'
            }

        }
    }
}
</script>

<template>
  <div class="home-container">
      <h1>Home</h1>
      <card>
          <!-- 作用域插槽  v-slot:插槽名 = '接受子组件数据的对象名,可自定义'  v-slot : 插槽名称 = ' 传过来的值 '-->
          <template v-slot:scope_slot = 'item'>
              <h1>{{item.text.msg}}</h1>
              <div v-for="u in item.user" :key='u'>
                  <h3>{{u.name}}</h3>
              </div>
          </template>
          
          <!-- 具名插槽 v-slot:插槽名字 -->
          <template v-slot:named_slot>
              <h1>具名插槽</h1>
          </template>


          <template>
              <h1>匿名插槽</h1>
          </template>
      </card>
  </div>
</template>

缩写方式

<template>
  <div class="home-container">
      <h1>Home</h1>
      <card>
          <!-- 2.6.0 之后  具名插槽 v-slot:scope_slot  可以缩写为 #scope_slot  ,
          必须是有参数才能这样写!!! # = "xxx "  这样是不行的 
            #default = 'xxx' 这样才可以-->

          <template #scope_slot = 'item'>
              <h1>{{item.text.msg}}</h1>
              <div v-for="u in item.user" :key='u'>
                  <h3>{{u.name}}</h3>
              </div>
          </template>
          
          <!-- 具名插槽 v-slot:插槽名字 -->
          <template #named_slot>
              <h1>具名插槽</h1>
          </template>


          <template>
              <h1>匿名插槽</h1>
          </template>
      </card>
  </div>
</template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值