首页 > 其他 > 详细

vue中的插槽

时间:2020-03-22 15:08:57      阅读:53      评论:0      收藏:0      [点我收藏+]

1、具名插槽

父组件:
	<template>
  <div>
    <div>
      <h1>我是头部</h1>
      <slot name="head"></slot>
    </div>

    <div>
      <h1>我是尾部</h1>
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {}
  }
}
</script>
子组件:
	<template>
  <div id="app">
    <Index>
      <template v-slot:footer>
        <p>这里是footer</p>
      </template>
      <template v-slot:head>
        <p>这里是head</p>
      </template>
    </Index>
  </div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
  name: ‘app‘,
  components: {
    Index
  }

}
</script>
接下来我们将子组件插槽的名字调换一下,父组件不变
<template>
  <div id="app">
    <Index>
      <template v-slot:head>
        <p>这里是head</p>
      </template>
        <template v-slot:footer>
        <p>这里是footer</p>
      </template>
    </Index>
  </div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
  name: ‘app‘,
  components: {
    Index
  }

}
</script>
由此看出,即使父组件对插槽的填充的顺序打乱,只要名字对应上了,就可以正确渲染到对应的插槽中。即: 父组件填充内容时,是可以根据这个名字把内容填充到对应插槽中的

2、默认插槽(默认插槽就是指没有名字的插槽,子组件未定义的名字的插槽,父级将会把 未指定插槽的填充的内容填充到默认插槽中)

<template>
  <div id="app">
    <Index>
      <template v-slot:footer>
        <p>这里是footer</p>
      </template>
      <template v-slot:head>
        <p>这里是head</p>
      </template>
      <template>
        <p>这里是默认插槽</p>
        <p>aaaaa</p>
      </template>
    </Index>
  </div>
</template>
<script>
import Index from ‘./components/index.vue‘
export default {
  name: ‘app‘,
  components: {
    Index
  }

}
</script>
父组件插槽:
<template>
  <div>
    <div>
      <h1>我是头部</h1>
      <slot name="head"></slot>
    </div>
     <div>
      <h1>我是默认插槽</h1>
      <slot></slot>
    </div>
    <div>   
      <h1>我是尾部</h1>
      <slot name="footer"></slot>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {}
  }
}
</script>

注意:

父级的填充内容如果指定到子组件的没有对应名字插槽,那么该内容不会被填充到默认插槽中。
 如果子组件没有默认插槽,而父级的填充内容指定到默认插槽中,那么该内容就“不会”填充到子组件的任何一个插槽中
 如果子组件有多个默认插槽,而父组件所有指定到默认插槽的填充内容,将“会” “全都”填充到子组件的每个默认插槽中。

vue中的插槽

原文:https://www.cnblogs.com/cc0419/p/12545941.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!