vue3的新写法和特性整理——六、插槽的使用

1、子组件暴露插槽的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
  <div class="hello">
    <h1>子组件</h1>
    <h1>↓↓↓以下是默认插槽内容↓↓↓</h1>
    <slot :scope="sexEn1"></slot>
    <h1>↑↑↑以上是插槽内容↑↑↑</h1>
    <br />
 
    <div>{{sexEn}}</div>
    <h1>↓↓↓以下是具名插槽 sex的内容↓↓↓</h1>
    <slot name="sex" :scope="sexEn2"></slot>
    <h1>↑↑↑以上是具名插槽 sex的内容↑↑↑</h1>
  </div>
</template>
 
<script>
import { reactive, toRefs } from 'vue';
export default {
  setup(a,b) {
    console.log(b);
    const state = reactive({
      sexEn1: 'femeal',
      sexEn2: 'meal',
      age: 23
    });
    return {
      ...toRefs(state)
    };
  },
  name: 'AgeAndSex'
};
</script>
 
<style scoped>
.hello {
  margin: 20px;
  color: green;
  border: 1px solid green;
}
.pointer {
  cursor: pointer;
}
</style>

  
2、父组件使用插槽的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<template>
  <div class="about">
    <AgeAndSex>
      <template v-slot="obj">
        <div class="slot">父组件使用插槽反显sexEn1:{{obj.scope}}为{{filter(obj.scope)}}</div>
      </template>
      <template v-slot:sex="obj">
        <div class="slot">父组件使用插槽反显sexEn2:{{obj.scope}}为{{filter(obj.scope)}}</div>
      </template>
    </AgeAndSex>
  </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import { reactive, toRefs } from 'vue';
import AgeAndSex from '@/components/AgeAndSex';
export default {
  setup() {
    let filter = e => {
      console.log(e);
      switch (e) {
        case 'meal':
          return '男';
        case 'femeal':
          return '女';
        default:
          return '保密';
      }
    };
    return {
      filter
    };
  },
  filters: {},
  components: { AgeAndSex }
};
</script>
<style scoped>
.slot {
  color: red;
}
</style>

  效果图

 

 

3、顺带一提:在vue3中,已经废除了管道符(过滤器)的功能,官方提出使用计算属性的解决方案。如果复用性不高,也可以在setup中写方法,或者写在工具函数里(我个人想法是挂载到window上,然后在setup中的返回值中解构)

本文作者:我吃柠檬

本文链接:https://www.cnblogs.com/yjc-vue-react-java/p/13876723.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   我吃柠檬  阅读(1667)  评论(0编辑  收藏  举报
编辑推荐:
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
阅读排行:
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· 一文搞懂MCP协议与Function Call的区别
· 如何不购买域名在云服务器上搭建HTTPS服务
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起