Skip to main content

Command Palette

Search for a command to run...

通过一个demo再次理解v-slot

Published
1 min readView as Markdown
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <div id="app">
    <!-- v-slot="slotProps" 拿到 slot属性给 slotProps -->
    <my-list title="shapes" v-slot="slotProps" :items="shapes">
      <div><span>{{slotProps.item.name}}:({{slotProps.item.sides}})sides</span></div>
    </my-list>
    <my-list title="colors" v-slot="slotProps" :items="colors">
      <div>{{title}}</div>
      <div :style="{background: slotProps.item.hex}">{{ slotProps.item.name }}</div>
    </my-list>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>

  <script type="text/x-template" id="my-list">
    <div>
      <div>{{title}}</div>
      <div v-for="item in items">
        <!-- slot属性:{item} -->
        <slot :item="item"></slot>
      </div>
    </div>
  </script>
  <script>
    Vue.component('myList', {
      template: '#my-list',
      props: {
        title: String,
        items: Array,
      }
    })
    new Vue({
      el: '#app',
      data: {
        shapes: [
          { name: 'Square', sides: 4 },
          { name: 'Hexagon', sides: 6 },
          { name: 'Triangle', sides: 3 }
        ],
        colors: [
          { name: 'Yellow', hex: '#F4D03F', },
          { name: 'Green', hex: '#229954' },
          { name: 'Purple', hex: '#9B59B6' }
        ]
      }
    });
  </script>
</body>

</html>

More from this blog

EddieQiao's blog

84 posts

coder, work in suzhou