组件需求
点击输入框, 弹窗显示表格,然后选择记录,
结果: 组件的绑定的值为对应主键, 但是显示值为对应名称。
效果
组件代码
<template>
<el-input @click="dialogVisible = true" v-model="showName">
</el-input>
<el-dialog
v-model="dialogVisible"
title="请选择"
width="80%"
:before-close="handleClose"
@open="beforeOpen"
>
<el-table :data="tableData" border class="table" v-loading="loading"
@selection-change="handleSelectionChange">
<el-table-column type="selection" width="55"/>
<el-table-column :prop="label" label="名称" align="center"/>
</el-table>
<el-pagination
class="pagination"
v-model:currentPage="currentPage"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
>
</el-pagination>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleOk"
>确定</el-button
>
</span>
</template>
</el-dialog>
</template>
<script>
import request from "../util/request";
export default {
name: "Naruto-Select",
data() {
return {
tableData: [],
loading: false,
dialogVisible: false,
currentPage: 1,
pageSize: 10,
total: 0,
selection: [],
showName: ''
}
},
props: {
id: {
type: String,
required: false
},
baseUrl: {
type: String,
required: true
},
label: {
type: String,
required: true
}
},
emits: ['update:id'],
watch: {
id: {
immediate: true,
handler(val, oldVal) {
if (!val) {
this.showName = '';
return;
}
if (val && val !== oldVal) {
this.getById(val);
}
}
}
},
methods: {
getById(id) {
let params = {id}
request.get(`/api/${this.baseUrl}/get`, {params}).then((res) => {
if (res.success) {
this.showName = res.data[this.label];
}
})
},
handleOk() {
if (this.selection.length !== 1) {
this.$message.warning(`请选择单条记录`);
return;
}
this.showName = this.selection[0][this.label];
this.$emit(`update:id`, this.selection[0].id);
this.handleClose();
},
handleSelectionChange(val) {
this.selection = val;
},
beforeOpen() {
this.get();
},
get() {
let params = {
pageNo: this.currentPage,
pageSize: this.pageSize
}
this.loading = true
request.get(`/api/${this.baseUrl}/list`, {params}).then((res) => {
this.loading = false
if (res.success) {
this.total = res.data.total;
this.tableData = res.data.records;
}
})
},
handleSizeChange(val) {
this.pageSize = val;
this.currentPage = 1;
this.get();
},
handleCurrentChange(val) {
this.currentPage = val;
this.get();
},
handleClose() {
this.dialogVisible = false;
}
}
}
</script>
<style scoped lang="less">
.pagination {
padding-top: 10px;
text-align: right;
}
</style>
import mySelect from './components/Naruto-Select.vue'
<my-select v-model:id="form.parentId" label="menuName" baseUrl="/service-admin/platform_menu"></my-select>