Vue-插槽学习

本文详细介绍了Vue.js中插槽(slot)的使用方法,包括具名插槽和作用域插槽。通过实例展示了如何在父组件中定义插槽内容,并在子组件中展示,同时演示了如何通过slot-scope获取子组件的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <child1>
      <header slot='header'>插槽header</header>
      <footer slot='footer'>插槽footer</footer>
    </child1>
    <hr/>
    <!-- 当我们使用 <child2> 组件的时候,我们可以选择为text定义一个不一样的 <template> 作为替代方案,
    并且可以通过 slot-scope 特性从子组件获取数据: -->
    <child2>
      <template slot-scope="slotProps">
        <p>第1个child2组件text是h1</p>
        <h1>{{slotProps.text}}</h1>
      </template>
    </child2>
    <child2>
      <template slot-scope="slotProps">
        <p>第2个child2组件text是h2</p>
        <h2>{{slotProps.text}}</h2>
      </template>
    </child2>
  </div>
</body>
<script type="text/javascript" src="./vue.js"></script>
<script>
Vue.prototype.bus=new Vue();
//具名插槽
Vue.component('child1',{
  template:`
     <div>
       <slot name='header'></slot>
       <p>child1内容</p>
       <slot name='footer'></slot>
     </div>
  `,
})
//作用域插槽
//使用场景:我们希望每个child2组件都有可复用数据text,但是渲染出第东西又不太一样。
Vue.component('child2',{
  data:function(){
    return{
      text:'子组件数据'
    }
  },
  template:`
     <div>
       <p>child2内容</p>
       <slot :text=text></slot>
     </div>
  `,
})
var app=new Vue({
    el:'#app',
})
</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值