Vue 插槽的使用

插槽的基本分类:

  1. 默认插槽
  2. 具名插槽
  3. 作用域插槽

默认插槽:

父组件:

<template>
  <div class="father">
    <h3>这里是菜单</h3>
    <child>
      <div class="list">
        <li>口水鸡</li>
        <li>口水鸭</li>
        <li>口水猪</li>
        <li>口水驴</li>
        <li>口水羊</li>
        <li>口水牛</li>
      </div>
    </child>
  </div>
</template>

<script>
import child from '@/components/Child';

export default {
  components:{
    child
  }
};
</script>

 子组件:

<template>
  <div class="child">
    <h3>这里是餐桌点餐</h3>
    <slot></slot>
  </div>
</template>

具名插槽:

父组件:

<template>
  <div class="father">
    <h3>这里是菜单</h3>
    <child>
      <template slot="header">
        <h1>Here might be a page title 1111</h1>
      </template>

      <p>默认插件1</p>
      <p>默认插件2</p>

      <div slot="footer">
        <p>Here's some contact info 2222</p>
      </div>
    </child>
  </div>
</template>

<script>
import child from "@/components/Child";

export default {
  name: "HelloWorld",
  components: {
    child
  }
};
</script>

 子组件:

<template>
  <div>
    <slot name="header"></slot>

    <slot></slot>
    
    <slot name="footer"></slot>
  </div>
</template>

 作用域插槽:

父组件:

<template>
  <div class="father">
    <child>
      <template slot-scope="user">
        <ul>
          <li v-for="item in user.data">{{item}}</li> // 对应子组件里面的data值
          <li v-for="item in user.aaaa">{{item}}</li>
        </ul>
      </template>
    </child>
  </div>
</template>

<script>
import child from "@/components/Child";

export default {
  name: "HelloWorld",
  components: {
    child
  }
};
</script>

子组件:

<template>
  <div class="child">
    <slot :data="value"></slot>
    <slot :aaaa="data"></slot>
  </div>
</template>

<script>
export default {
  data () {
    return {
      data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba'],
      value: ['1','2','3','4','5','6']
    };
  }
};
</script>

 

posted @ 2022-12-06 22:20  轻风细雨_林木木  阅读(7)  评论(0编辑  收藏  举报