默认插槽

  1. 父组件中:
  2. <Category>
  3. <div>html结构1</div>
  4. </Category>
  5. 子组件中:
  6. <template>
  7. <div>
  8. <!-- 定义插槽 -->
  9. <slot>插槽默认内容...</slot>
  10. </div>
  11. </template>

具名插槽

  1. 父组件中:
  2. <Category>
  3. <template slot="center">
  4. <div>html结构1</div>
  5. </template>
  6. <template v-slot:footer>
  7. <div>html结构2</div>
  8. </template>
  9. </Category>
  10. 子组件中:
  11. <template>
  12. <div>
  13. <!-- 定义插槽 -->
  14. <slot name="center">插槽默认内容...</slot>
  15. <slot name="footer">插槽默认内容...</slot>
  16. </div>
  17. </template>

作用域插槽

理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

  1. 父组件中:
  2. <Category>
  3. <template scope="scopeData">
  4. <!-- 生成的是ul列表 -->
  5. <ul>
  6. <li v-for="g in scopeData.games" :key="g">{{g}}</li>
  7. </ul>
  8. </template>
  9. </Category>
  10. <Category>
  11. <template slot-scope="scopeData">
  12. <!-- 生成的是h4标题 -->
  13. <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
  14. </template>
  15. </Category>
  16. 子组件中:
  17. <template>
  18. <div>
  19. <slot :games="games"></slot>
  20. </div>
  21. </template>
  22. <script>
  23. export default {
  24. name:'Category',
  25. props:['title'],
  26. //数据在子组件自身
  27. data() {
  28. return {
  29. games:['红色警戒','穿越火线','劲舞团','超级玛丽']
  30. }
  31. },
  32. }
  33. </script>