插槽之面试踩坑~

140 阅读1分钟

一道面试题~

问,如何做到这样一个布局,上边是子组件内容,下边是子组件内容,中间是父组件内容。

这个问题就是一道插槽的问题,如果对插槽不熟悉,这个可以加深记忆,上代码

父组件

<template>
    <div>
      <el-son >
        <div class="son">
          这里是父组件内容
        </div>
      </el-son>
    </div>
</template>

<script>
import ElSon from './components/son'//引入自组件
export default {
  name: 'parent',
  components: {
    ElSon
  }
}
</script>

<style scoped lang="stylus">
.son
  width:100px
  height:100px
  background-color:green
</style>

子组件

<template>
    <div class="container">
      <div>这里是子组件</div>
      <slot></slot>//这里是插槽,用来接收父组件的内容
      <div>这里是子组建</div>
    </div>
</template>

<script>
export default {
  name: 'son',
}
</script>

<style scoped lang='stylus'>
.container
  width:200px
  height:200px
  background-color:red
</style>

效果~