我们在键盘上留下的余温, 也将随时代传递到更远的将来


:D 获取中...

收集工作中使用 Vue 遇到的一些问题

封装组件时 slot 的处理

最近在优化以前基于 ElementUI 封装的上传组件时(上传文件时加一个进度条), 发现同样的代码, 使用 ElementUI 和自己封装的组件样式不一样:

different

这里是源码, 当然已经修改好了

封装组件修改前的简略代码:

1
2
3
4
5
6
7
8
9
10
<template>
<el-upload
ref="upload"
class="upload-file"
>
<slot name="trigger"></slot>
<slot><el-button type="primary" size="small">点击上传</el-button></slot>
<slot name="tip"></slot>
</el-upload>
</template>

调用组件的简略代码:

1
2
3
4
5
6
<upload-file
action="https://jsonplaceholder.typicode.com/posts/"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</upload-file>

审查元素发现自己的 .el-upload 既包含了上传按钮, 也包含了提示文字:

.el-upload

ElementUI.el-upload 只包含上传按钮, 提示文字和它是兄弟元素

.el-upload

最后自己跟着代码走了一遍后发现问题所在了: 自己封装的时候, slot 确实起作用了, 但只起到了接收传入的值的功能; 传入到 el-upload 后, 并没有给这些标签加 slot, 就变成这样了:

1
2
3
4
5
6
7
<el-upload
ref="upload"
class="upload-file"
>
<el-button size="small" type="primary">点击上传</el-button>
<div class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>

所以 el-upload 就把这两个标签都当成默认插槽了, 都放到 .el-upload 这个标签里面了.

所以封装组件中这两个 slot 不仅要承担接收外部传入的值, 还承担了将这些值传入到 el-upload 中的功能:

1
2
3
4
5
6
7
8
<el-upload
ref="upload"
class="upload-file"
>
<slot name="trigger" slot="trigger"></slot>
<slot><el-button type="primary" size="small">点击上传</el-button></slot>
<slot name="tip" slot="tip"></slot>
</el-upload>

所以以后封装组件需要加具名 slot 时, 一定要把 nameslot 这两个属性都加上


 评论

 无法加载Disqus评论系统,请确保您的网络能够正常访问。