Vue-插槽学习

<!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>

猜你喜欢

转载自www.cnblogs.com/superlizhao/p/9633151.html