How to use v-model and promise to implement vue pop-up component
This time I will show you how to use v-model and promise to implement the vue pop-up component, and how to use v-model and promise to implement the vue pop-up component. What are the precautions , the following is a practical case, let’s take a look.
Recently, the company has a back-end business that is written in the existing back-end system, but later it needs to be pulled out to create a new back-end system separately for this business, so the vue component library in the existing back-end system, It can no longer be used (because I don’t know what component library the future system will be based on to prevent trouble from future transplant projects). This time I encountered the pop-up function in the business, so I can only write one manually (although it is The pop-up window component is very simple, and I want to summarize it myself. Please point out if there are any mistakes). At first, I used traditional props and $emit, but I felt that the logic of needing to receive two cancellation and confirmation callbacks was scattered, so I used Writing the two callbacks together instead of two promise callbacks is not necessarily a good idea, but it provides an idea.
1. Overview
Let’s first look at the final calling method
props $emit method
<chat-modal> <p>slot的东西,想向弹窗中添加自定义的内容</p> </chat-modal> methods: { display() { this.showModal = true;//交互点击手动触发显示弹窗 }, onOK() {},//点击确认的回调 onCancel() {}//点击取消的回调 }
Promise callback method
<chat-modal></chat-modal> methods: { display() { this.$refs["chat-modal"].openModal({ title: "弹窗标题", sureText: "确认", cancelText: "取消" }).then(res => { //点击确认的回调 }, res => { //点击取消的回调 }) } }
The advantage of the second method is that all the logic is concentrated into one method.
2. Take a look at the source code of the component
tip: The style is a bit bad...
<template> <p> </p> <p></p> <p> </p> <p>{{ otherText.title || title}}</p> <p> <slot></slot> </p> <p> </p> <p>{{ otherText.sureText || sureText }}</p> <p>{{ otherText.cancelText || cancelText }}</p> </template> <script> //此组件提供两种调用方法,可以在组件上v-model一个表示是否显示弹窗的对话框,然后需要的一些值通过props传入,然后$emit在组件上@监听做回调 //第二中方法所有的传值回调都只需要在组件内部的一个方法调用然后在组件外部this.$refs[xxx].open调用然后.then触发回调,比上一种方便些 var initOtherText = { sureText: "", cancelText: "", title: "", small: false }; export default { props: { title: { type: String }, sureText: { type: String }, cancelText: { type: String }, value: { type: Boolean }, small: { type: Boolean } }, watch: { value(newVal) { this.showModal = newVal; } }, data() { return { otherText: JSON.parse(JSON.stringify(initOtherText)), showModal: this.value }; }, methods: { makeSure() { this.$emit("on-ok"); this.$emit("input", false); }, makeCancel() { this.$emit("on-cancel"); this.$emit("input", false); }, openModal(otherText) { this.otherText = { ...otherText }; this.showModal = true; var pms = new Promise((resolve, reject) => { this.$refs["sure"].addEventListener("click", () => { this.showModal = false; resolve("点击了确定"); }); this.$refs["cancel"].addEventListener("click", () => { this.showModal = false; reject("点击了取消"); }); }); return pms; } } }; </script> <style> .shadow { background-color: rgba(0, 0, 0, 0.5); display: table; height: 100%; left: 0; position: fixed; top: 0; transition: opacity 0.3s ease; width: 100%; z-index: 50; } .modal { display: table-cell; vertical-align: middle; overflow-x: hidden; position: fixed; background-color: white; box-shadow: rgba(0, 0, 0, 0.33) 0px 2px 8px; border-radius: 5px; outline: 0px; overflow: hidden; transition: all 0.3s ease; width: 600px; height: 400px; top: 50%; left: 50%; margin-top: -200px; margin-left: -300px; } .header { align-items: center; background-color: #62a39e; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.16); color: #fff; font-weight: bold; display: -ms-flexbox; display: flex; height: 3.5rem; padding: 0 1.5rem; position: relative; z-index: 1; } .body { align-items: center; padding: 1.5rem; } .footer { justify-content: flex-end; padding: 1.5rem; position: absolute; bottom: 0; width: 100%; float: right; } .item { color: white; text-align: center; border-radius: 5px; padding: 10px; cursor: pointer; display: inline-block; } .info { background-color: #2196f3; } .success { background-color: #62a39e; } .red { background-color: #e95358; } .smSize { height: 200px; } </style>
First analyze the first One way: the caller needs to bind a variable (showModal in this example) to the v-model outside the component to indicate whether the pop-up window is displayed. When displayed, it needs to be manually set outside the component this.showModal = true
, the props inside the component define an attribute to take this value as value: {type: Boolean}, and declare a variable inside the component to synchronize the props value passed in from the outside. The default value is showModal: this.value (internal declaration The value is also called showModal), listen in the watch for synchronization watch: { value(newVal) { this.showModal = newVal } }
; Then bind the showModal value inside the component to the location that needs to be displayed or On hidden DOM elements. The event is thrown outward when the OK and close buttons inside the component are clicked
makeSure() { this.$emit("on-ok"); this.$emit("input", false); }, makeCancel() { this.$emit("on-cancel"); this.$emit("input", false); }
this.$emit("on-ok");this.$emit("on-cancel" );
These two sentences are about throwing events out, receiving them outside the component, and then writing the callback function that you need. At this time, the pop-up window can be displayed and hidden. You may find that there is no code to set this.showModal = false; the pop-up window is hidden. Mainly because of these lines of code v-model = 'showModal' and props: {value: {type: Boolean}} this.$emit("input", false)
inside the component. v-model is actually syntactic sugar for vue, <chat-modal v-model="showModal"> </chat-modal>
In fact, it can be written as<chat-modal :value="showModal" arguments></chat-modal>
Therefore, we are required to specify that the names of props must be value inside the component, and then trigger this.$emit inside the component when confirming or canceling is triggered inside the component. ("input", false)
In this way, we can directly hide the pop-up window without disturbing the user and let the user manually set showModal to false outside the component.
Then look at the way of promise: The first way The values passed in are all received through props. This method defines another object inside the component to receive the passed in values.
var initOtherText = { sureText: "", cancelText: "", title: "", small: false }; otherText: JSON.parse(JSON.stringify(initOtherText)),
Then a method named openModal is defined in menthods. , and then assign the passed in series of parameters to the object inside the component this.otherText = { ...otherText }; this.showModal = true
; and set showModal to true, and then trigger each time When creating a new promise object, the asynchronous events inside are two click events, click OK and Cancel. Here we need to operate the DOM
this.$refs["sure"].addEventListener("click", () => { this.showModal = false; resolve("点击了确定"); });
Get the DOM element of the OK button to bind the click event, and set showModal to in the callback false and resolve,
this.$refs["cancel"].addEventListener("click", () => { this.showModal = false; reject("点击了取消"); });
Get the DOM binding click event of the cancel button, and reject in the callback.
The pitfalls encountered
I encountered a pit before, because the click event has been bound for the first time, and resolve and reject will fail the second time. I wanted to cancel the binding event, but because the entire pop-up window v- The reason why show="showModal"
is that the entire DOM is displayed:none; and there is no need to manually unbind it. The second one is about whether to use v-if or v-show to hide the pop-up window. I used v-if at the beginning but found that at this step
this.showModal = true; var pms = new Promise((resolve, reject) => { this.$refs["sure"].addEventListener.xxx//省略 }); return pms;
将showModal置为true时然后就去绑定事件这时候还没有DOM还没有解析玩DOM树上还没有,要不就得用this.$nextTick增加了复杂度,最后采用了v-show;
关于优先级问题
如果既在组件上用prop传了值(title,sureText之类的)如 <chat-modal title="xx" suretext="xxx"></chat-modal>
也在方法里传了
this.$refs["chat-modal"].openModal({ title: "服务小结", sureText: "提交并结束", cancelText: "取消" }).then();
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use v-model and promise to implement vue pop-up component. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools