8.作用域插槽
-- 未经授权禁止转载 --


作用域插槽

       子组件向父组件传递数据,并在父组件定义的模板中渲染


App.vue

<script setup>
  //导入子组件
  import Header from "./components/header.vue"
  import Footer from "./components/footer.vue"
</script>

<template>
  <h3>App.vue</h3>

  <!-- <Header/> -->
  <!-- 匿名插槽 -->
  <Header>
    <a href="http://dengruicode.com">邓瑞编程</a>
  </Header>

  <!-- 具名插槽 -->
  <Footer>
    <template v-slot:url>
      <a href="http://www.dengruicode.com">网址</a>
    </template>

    <!--
      v-slot:user 简写 #user

      作用域插槽
      子组件将url和title数据传递给 name="user" 的插槽,
      父组件通过 #user="data" 来接收这些数据

      <template #user="data">
        1000 {{ data.url }} {{ data.title }}
      </template>
    -->
    <!-- 解构 -->
    <template #user="{url,title}">
      1000 {{ url }} {{ title }}
    </template>
  </Footer>

</template>

<style scoped>

</style>


header.vue

<script setup>
    
</script>

<template>
    <h3>header.vue - 子组件</h3>

    <!-- 匿名插槽 -->
    <slot/>
</template>

<style scoped>

</style>


footer.vue

<script setup>
    
</script>

<template>
    <h3>footer.vue - 子组件</h3>

    <!-- 具名插槽 -->
    <slot name="url" />
    <slot name="user" url="dengruicode.com" title="邓瑞编程" />
</template>

<style scoped>

</style>