vue2弹窗选择记录
时间: 2025-03-31 17:06:33 浏览: 31
### Vue2 弹窗组件实现选择记录功能
以下是基于 Vue2 的弹窗组件实现选择记录功能的一个完整示例:
#### 1. 创建 `Notice` 函数用于动态挂载弹窗
通过创建一个通用的函数来动态挂载弹窗组件,可以方便地控制其显示和隐藏。
```javascript
// notice.js 文件
import Vue from 'vue';
function notice(Component, props) {
const vm = new Vue({
render(h) {
return h(Component, { props });
}
}).$mount();
document.body.appendChild(vm.$el);
const comp = vm.$children[0];
// 添加移除方法以便销毁实例
comp.remove = function () {
document.body.removeChild(vm.$el);
vm.$destroy();
};
return comp;
}
export default notice;
```
此部分代码实现了动态挂载任意 Vue 组件到页面上的逻辑[^1]。
---
#### 2. 定义弹窗组件 (ModalComponent.vue)
定义一个简单的弹窗组件,其中包含选项列表供用户选择,并提供回调接口将选中的数据返回给调用方。
```vue
<template>
<div class="modal">
<h3>请选择一条记录</h3>
<ul>
<li v-for="(item, index) in items" :key="index" @click="selectItem(item)">
{{ item }}
</li>
</ul>
<button @click="close">关闭</button>
</div>
</template>
<script>
export default {
name: "ModalComponent",
props: ["items"],
methods: {
selectItem(selectedItem) {
this.$emit("on-select", selectedItem); // 将选中项发送回父级
this.close(); // 关闭窗口
},
close() {
this.$emit("on-close"); // 发送关闭事件通知外部处理程序
}
}
};
</script>
<style scoped>
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style>
```
上述模板展示了如何构建一个基本的选择框界面以及相应的交互行为[^2]。
---
#### 3. 使用 Notice 挂载并获取反馈
在实际应用中可以通过如下方式使用该机制展示模态对话框并向外界报告最终选定的结果。
```javascript
// main.js 或其他业务逻辑入口处
import notice from './notice';
import ModalComponent from './components/ModalComponent.vue';
const openModalAndSelectRecord = async () => {
let selectedValue;
try {
const modalInstance = notice(ModalComponent, {
items: ['记录A', '记录B', '记录C'], // 提供给子组件的数据集合
onClose: () => console.log('User closed the dialog without selecting anything.'),
onSelect: value => {
selectedValue = value; // 记录下用户的操作结果
modalInstance.remove(); // 手动触发销毁流程释放资源占用情况
}
});
await Promise.race([
new Promise(resolve => setTimeout(() => resolve(), 10 * 1000)), // 设置超时时间防止无限等待状态发生
new Promise((resolve, reject) => {
Object.defineProperty(modalInstance, '$events', {
get() {
if (!this._listeners['on-select']) throw Error('Selection event not fired.');
else resolve(true);
}
})
})
]);
} catch(err){
alert(`Error during selection process:${err.message}`);
}
return selectedValue || null;
};
openModalAndSelectRecord().then(result => {
if (result !== null && result.length > 0 ) {
console.info(`Selected Record is ${result}.`);
} else{
console.warn('No record was chosen by user');
}
});
```
以上脚本片段说明了怎样利用前面提到过的工具类封装好的 API 来启动一次完整的交互过程,并捕获必要的元信息作为后续动作依据的一部分^.
---
###
阅读全文
相关推荐



















