Zhu xiaohang's blog

新版本的作用域插槽以及旧版本的slot

新版本的作用域插槽以及旧版本的slot

1.作用/概念:预先将使用的内容进行保留

我的理解就是父页面在组件标签内插入任意内容,子组件内插糟slot控制摆放位置(匿名插槽,具名插槽)

案例:

<body>  
	<div id='app'>
        <Hello>
            <div>
                这里是插入的内容	//这一部分的内容并不会被输出(原因是被组件覆盖掉了)	
            </div>
        </Hello>
    </div>

    <template id="hello">
        <div>
            <h3>这里是Hello组件</h3>
        </div>
    </template>
</body>
////////////////////////////////////////////////////////////////////////注册组件部分
<script>
    Vue.component('Hello', {
        template: '#hello'
    })

    new Vue({
        el: '#app'
    })
</script>

从上面的案例可以看出 直接在组件里面写元素是没有作用的,这时候就需要插槽slot

一旦在组件中加入加入的部分就会被显示出来

案例:

<template id="hello">
        <div>
            <slot></slot>
            <h3>这里是Hello组件</h3>
        </div>
    </template>

具名插槽

<body>
    <div id='app'>
        <Hello>
            <header slot='header'>这里是头部</header>	//这部插入的内容会被输出
            <footer>这里是底部</footer>		//这一部分内容不会被输出因为没有找到对应的插槽
        </Hello>
    </div>
    <template id="hello">
        <div>
            <slot name = "header"></slot>
            <h3>这里是Hello组件</h3>
            <slot name='footer'></slot>
        </div>
    </template>
</body>
<script>
    Vue.component('Hello', {
        template: '#hello'
    })

    new Vue({
        el: '#app'
    })
</script>

新版本的作用域插槽

作用域插槽: 子组件内数据可以被父页面拿到(解决了数据只能从父页面传递给子组件)

v-slot (目前该属性并不完善)

注意: 由于前两种插槽的形式在 vue2.6以上会被废弃,所以要使用v-slot指令来代替

v-slot的好处:

  1. 将具名插槽和作用域插槽进行统一
  2. 要将这两个属性带有vue的标识,并且符合vue两个最大的特性之一(指令的概念)

所以必须掌握

案例:

<div id="app">
    <Hello>
      <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>
    </Hello>
  </div>
  <template id ='hello'>
    <div class="container">
      <header>
        <!-- 我们希望把页头放这里 -->
        <slot name = "header"></slot>
      </header>
      <main>
        <!-- 我们希望把主要内容放这里 -->
      </main>
      <footer>
        <!-- 我们希望把页脚放这里 -->
        <slot name = 'footer'></slot>
      </footer>
    </div>
  </template>
</body>
posted @ 2019-06-29 17:32  mckk  阅读(395)  评论(0编辑  收藏  举报