前言
单例模式,顾名思义就是只有一个实例。在 Vue 中,应用到该设计模式的有 vuex、vue-route 等。
相关的设计模式和实现在网上可以找到很多教程,这里不做赘述。
在系统中,适合单例模式使用场景最常用的功能要算是登录了,本章节单讲登录弹窗的单例实现。
技术栈
vue 脚手架项目 + elementUI
elementUI 并非必要,样式和对话框样式可自己实现。
实现
在 components 中新建文件夹命名 loginDialog。在该目录下新建 index.js 和 LoginDialog.vue。

LoginDialog.vue
<template>
<el-dialog title="登录" :visible.sync="visible" width="30%" @close="visible = false">
<el-form ref="form" label-width="80px">
<el-form-item label="账号">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="form.password" type="password"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取 消</el-button>
<el-button type="primary" @click="visible = false">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: "loginDialog",
data() {
return {
visible: false,
form: {
name: "",
password: ""
}
};
},
components: {},
mounted() {},
methods: {
show() {
this.visible = true;
}
}
};
</script>
index.js
import vue from "vue";
import LoginDialog from "./LoginDialog.vue";
// 组件构造器,构造出一个 vue组件实例
const LoginConstructor = vue.extend(LoginDialog);
function Login() {
if (!this.instance) {
this.instance = new LoginConstructor({
el: document.createElement("div")
});
// 添加节点
document.body.appendChild(this.instance.$el);
}
return this.instance;
}
// 全局注册
function registryLogin() {
vue.prototype.$login = Login;
}
export default registryLogin;
最后,需要在 main.js 文件中,加入
import loginDialog from "./components/loginDialog/index";
Vue.use(ElementUI); // 注意,如果引入了 elementUI,需要放置在引用登录弹窗前
Vue.use(loginDialog);
使用
this.$login().show();
可以多调用几次 show 方法,看看是否只生成一次弹窗。


核心代码
function Login() {
if (!this.instance) {
this.instance = new LoginConstructor({
el: document.createElement("div")
});
// 添加节点
document.body.appendChild(this.instance.$el);
}
return this.instance;
}
上述代码只生产一个实例。
全局注册也可以写成
// 全局注册
function registryLogin() {
vue.prototype.$login = new Login();
}
调用
this.$login.show();

本文介绍了如何在Vue中利用单例模式实现登录弹窗组件的唯一实例。通过在components创建loginDialog文件夹,包含index.js和LoginDialog.vue,确保在整个应用中弹窗组件只会被实例化一次,避免多次生成登录对话框。文章提供核心代码展示,并说明在main.js中的注册和调用方法。
551

被折叠的 条评论
为什么被折叠?



