分析需求
我们在一个vue3的工程上引入了element-plus插件,用来简化我们的代码,其中element-plus中有一个标签名叫el-table用于展示多条结构类似的数据, 可对数据进行排序、筛选、对比或其他自定义操作,可以有效的使得代码编写更加的简洁。
但是我们发现,官网的代码示例,是基于一个简单的组件来写成的,并没有提及到如何给el-table中的元素添加相关的提示框。
解决方案
官网代码:使用Tooltip文字提示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <el-tooltip :visible="visible"> <template #content> <span>Content</span> </template> <el-button @mouseenter="visible = true" @mouseleave="visible = false"> Hover me </el-button> </el-tooltip> </template>
<script setup lang="ts"> import { ref } from 'vue'
const visible = ref(false) </script>
|
使用官网代码模板,然后决定定义一个插槽,让这个插槽中包含这个模板。决定使用以下方案:
1.定义插槽,将悬停框的所需要的数据传到方法中。
2.定义api接口
3.得到变量后在方法中,进行接口请求,获取所需要的代码。
4.将获得的内容,返回给内容提示框。
代码示例
定义插槽
1.定义插槽,将悬停框的所需要的数据传到方法中。
1 2 3 4 5 6 7 8 9 10 11 12 13
| <el-table v-loading="loading" :data="typeFunOrderList" style="width: 100%"> <el-table-column fixed label="订单号" align="left" prop="id" width="80" :show-overflow-tooltip="true" /> <el-table-column fixed label="TypeFun uid" align="left" prop="typeFunUid" width="175" :show-overflow-tooltip="true" /> <el-table-column label="学生ID" align="left" prop="stuId" width="80" :show-overflow-tooltip="true"> <!--引入弹框插槽,到学生ID列中,定义getStuId方法,将这一行的学生Id传给相应的方法,stuTimeContent进行内容接收--> <template #default="scope"> <el-tooltip effect="dark" :content="stuTimeContent" placement="top" trigger="hover"> <span @mouseenter="getStuId(scope.row.stuId)">{{ scope.row.stuId }}</span> </el-tooltip> </template> </el-table-column> </el-table>
|
定义API方法
2.定义api接口,在相应的API文件中
1 2 3 4 5 6 7 8
| import request from '@/utils/request'
export function stuTime(stuId){ return request({ url:'third/typefun/stuAccount/get/' + stuId, method:'get' }) }
|
引入接口编写接收Id方法
3.得到变量后在方法中,进行接口请求,获取所需要的代码。(一般在views或者pages中的vue组件中)
1 2 3 4 5 6 7
| let stuTimecontent = ref() const getStuId = (stuId) => { stuTimeApi(stuId).then((res) => { const stuInfo = res.data; stuTimecontent.value = `${stuInfo.stuName}:${stuInfo.startTime}——${stuInfo.endTime}`; }) }
|
内容传递给提示框
4.将获得的内容,返回给内容提示框。
在1的部分是完整的代码,stuTimeContent用来传递新的信息
1
| <el-tooltip effect="dark" :content="stuTimeContent" placement="top" trigger="hover">
|