preface

Many websites have permission control. For example, in the comment system of some blog websites, users must log in before they can make comments. If they do not log in and want to make comments, the website will pop up a login popup window. The login popover can pop up wherever permissions are needed, so we must encapsulate the popover component as a common, common global call.

1. Write the login popup component

Create LoginDialog. Vue login popover file, write component basic code, login popover style by yourself.

Async userLogin() {let params = {email: this.formlogin. email, password: this.formLogin.password, }; const data = await userLogin(params); If (data.code === "00000") {this.$message. Success (" login successfully "); this.login(data); // Call this.close(); } else {this.$message({message: data.message, type: "error",}); }},Copy the code

2. Write global component registration code

Create a new LoginDialog. Js file to register popover components as global components.

import Vue from "vue"; import login from ".. /components/LoginDialog/LoginDialog.vue"; Const LoginDialog = vue.extend (login); // Import popover const LoginDialog = vue.extend (login); login.install = function(data) { let instance = new LoginDialog({ data, }).$mount(); document.body.appendChild(instance.$el); Vue.nextTick(() => { instance.open(); }); }; export default login; / / exportCopy the code

3. Mount the component to the prototype

Import LoginDialog. Js in main.js and mount it globally.

import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import store from "./store"; import login from "./common/LoginDialog"; Prototype.$login = login.install; // This.$login can be used globally to call vue.config. productionTip = false; new Vue({ router, store, render: (h) => h(App), }).$mount("#app");Copy the code

4. Call globally anywhere

For example, the login button in the navigation bar, after clicking, we directly call up the popover, and can register the callback function. For example, click the login button in the Login popup and execute the login callback function if the login succeeds.

OpenLoginDialog () {this.$login({login: (data) => {if (data) {// Login callback function}}, register: (data) => {if (data) {// register callback function}},}); },Copy the code

In addition to the navigation bar, it can also be written in the route front, when the user wants to access a page without permission, the login popup window will pop up.

import router from "@/router/index"; import login from ".. /common/LoginDialog"; BeforeEach ((to, from, next) => {let token = localstorage.getitem ("token"); if (token || ! to.meta.auth) { next(); } else { if (to.path === "/") { next(); } else { login.install(); }}});Copy the code

conclusion

One of the most important aspects of encapsulating the global registry login popover is how to globally register components in the Vue scaffolding.