Vue笔记12-Vue插槽使用

注意
本文最后更新于 2024-05-18,文中内容可能已过时。

简单使用

TestView.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<script setup lang="ts">
</script>
<template>
<div class="parent">
    <slot>
    </slot>
</div>
</template>
<style scoped>
.parent {
    width: 100px;
    height: 100px;
    background-color: aquamarine;
}
</style>

HomeView.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<script setup lang="ts">
import TestView from '../views/TestView.vue'
</script>
<template>
  <div>
<TestView>
  <template v-slot>
    <p>HelloWOrld</p>
  </template>
</TestView>
  </div>
</template>
<style scoped>

</style>

具名插槽

TestView.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<script setup lang="ts"></script>
<template>
  <div class="parent">
    <slot name="header"></slot>
    <slot> </slot>
    <slot name="footer"></slot>
  </div>
</template>
<style scoped>
.parent {
  width: 100px;
  height: 100px;
  background-color: aquamarine;
}
</style>

HomeVIew

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<script setup lang="ts">
import TestView from '../views/TestView.vue'
</script>
<template>
  <div>
<TestView>
  <template v-slot:header>
    <p>header</p>
  </template>
  <template v-slot>
    <p>body</p>
  </template>
  <template v-slot:footer>
    <p>footer</p>
  </template>
</TestView>
  </div>
</template>
<style scoped>

</style>

作用域插槽

HomeView.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<script setup lang="ts">
import TestView from '../views/TestView.vue'
</script>
<template>
  <div>
<TestView>
  <template v-slot:header>
    <p>header</p>
  </template>
  <template v-slot="{data}">
    <p>body{{ data }}</p>
  </template>
  <template v-slot:footer>
    <p>footer</p>
  </template>
</TestView>
  </div>
</template>
<style scoped>

</style>

TestView.vue

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<script setup lang="ts">
import {ref} from 'vue';
let data = ref("meowrain");
</script>
<template>
  <div class="parent">
    <slot name="header"></slot>
    <slot :data="data"> </slot>
    <slot name="footer"></slot>
  </div>
</template>
<style scoped>
.parent {
  width: 100px;
  height: 100px;
  background-color: aquamarine;
}
</style>

https://blog.meowrain.cn/api/i/2024/01/22/1170g4s-3.webp


相关内容

0%