Vue3,插槽,slot,单个slot,具名slot,作用域slot,案例代码

Vue3,插槽,slot,单个slot,具名slot,作用域slot,案例代码

技术教程gslnedu2025-04-23 13:20:459A+A-

插槽(slot)

插槽,也就是slot,是组件的一块HTML模板,一个slot最核心的两个问题是显示不显示和怎样显示。

插槽,子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。

单个slot

单个插槽,别名默认插槽、匿名插槽,不用设置name属性。

具名slot

给插槽起一个名字,插槽加了name属性,就变成了具名插槽。具名插槽可以在一个组件中出现N次,出现在不同的位置。

作用域slot

vue2.5版本中slot-scope取代了scope,来实现作用域插槽,主要用在组件调用中,具体在template标签上面使用slot-scope来获取插槽slot上面的属性值,获取值的为一个对象,slot-scope=”它可以取任意字符串”,在element-ui的组件中经常看到。

案例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue,插槽slot</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
</head>
<body>
<div id="app">
  <!-- 单个插槽,别名默认插槽、匿名插槽,不用设置name属性 -->
  <children1>
    <span>12345</span>
  </children1>
  <!-- 插槽加了name属性,就变成了具名插槽。具名插槽可以在一个组件中出现N次,出现在不同的位置 -->
  <children2>
    <span slot="first" @click="handFirst">12345</span>
    <span slot="second">56789</span>
  </children2>
  <!-- 将数据传递给组件 -->
  <tb-list :data="data">
    <!-- 获取slot上面的值 -->
    <template slot-scope="scope">
      <!-- {"row":{"name":"张三","age":"39","sex":"男"},"$index":0} -->
      <p>row:{{JSON.stringify(scope)}}</p>
      <p>索引:{{scope.$index}}</p>
      <p>姓名: {{scope.row.name}}</p>
      <p>年龄: {{scope.row.age}}</p>
      <p>性别: {{scope.row.sex}}</p>
    </template>
  </tb-list>
</div>

<script type="text/javascript">
  var app = new Vue({
    el: '#app',
    data: {
      data: [{
        name: '张三',
        age: '39',
        sex: '男'
      }]
    },
    methods: {
      handFirst: function () {
        console.log("It is the parent's method");
      }
    },
    components: {
      // 单个slot
      children1: {
        template: "<button><slot></slot>单个插槽</button>"
      },
      // 具名slot
      children2: {
        template: "<button><slot name='first'></slot>具名插槽,<slot name='second'></slot></button>"
      },
      // 作用域slot
      'tb-list': {
        template:
            `<ul>
                <li v-for="(item, index) in data">
                    <slot :row="item" :$index="index"></slot>
                </li>
            </ul>`,
        // 获取值
        props: ['data']
      }
    }
  });
</script>
</body>
</html>
点击这里复制本文地址 以上内容由朽木教程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

朽木教程网 © All Rights Reserved.  蜀ICP备2024111239号-8