Vue slot插槽详解

slot官网

  • 子组件挂载父组件上面,父组件数据传给子组件,子组件决定数据展示位置;
  • 子组件添加 接受父组件传过的值,

Home.vue

<template>
  <div class="home">
    <homeChildren>
      <template v-slot:header="{ objChildren1 }">
        这里是顶栏 <br>
        接受子组件data数据为:{{objChildren1.name}}  // 拿到子组件数据
      template>

      <template v-slot:footer="{ objChildren2 }">
        这里是低栏 <br>
        接受子组件data数据为: {{objChildren2.name}} // 拿到子组件数据
      template>

      <template v-slot:todo="{ todo }">
        {{ todo.text }}
      template>
    homeChildren>
  div>
template>
<script>
import homeChildren from '../components/homeChildren.vue'
export default {
  name: 'Home',
  components: {
    homeChildren
  },
  data(){
    return{
      home1:'父组件值1'
    }
  }
}
script>

homeChildren.vue

<template>
  <div class="page">
    <div class="header">
      <span style="color:lightsalmon">header下面为父组件想要展示内容: <br>span>

      <slot name="header" :objChildren1="homeObj1">slot>


      
    div>
    <div class="footer">
      <span style="color:lightsalmon">footer下面为父组件想要展示内容: <br>span>

      <slot name="footer" :objChildren2="homeObj2">slot>
    div>

    <div>
      todo: <br>
      <slot name="todo" :todo="todo">slot>
    div>
  div>
template>

<script>
export default {
  data () {
    return {
      homeObj1: {
        name: 'one slot'
      },
      homeObj2: {
        name: 'two slot'
      },
      todo: {
        text: '这里是文本'
      }
    }
  }
}
script>


<style lang="scss" scoped>
.page {
  width: 100%;
  display: flex;
  flex-direction: column;
  .header {
    height: 200px;
    border-bottom: 1px solid #ccc;
  }
  .footer {
    height: 200px;
    border-bottom: 1px solid #ccc;
  }
}
style>

效果如下图

Vue slot插槽详解_第1张图片

博客推荐

博主1
博主2
博主3

最后

感觉文章好的话记得点个心心和关注和收藏,有错的地方麻烦指正一下,如果需要转载,请标明出处,多谢!!!

你可能感兴趣的:(vue,html,js方法,vue.js,前端,javascript)