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 ref="chat-modal" v-model="showModal" cancelText="取消" sureText="确认" title="弹窗标题" small @on-ok="onOK" @on-cancel="onCancel"> <p>slot的东西,想向弹窗中添加自定义的内容</p> </chat-modal> methods: { display() { this.showModal = true;//交互点击手动触发显示弹窗 }, onOK() {},//点击确认的回调 onCancel() {}//点击取消的回调 }
Promise callback method
<chat-modal ref="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 class="shadow" v-show="showModal"></p> <p class="modal" :class="{'smSize': otherText.small || small}" v-show="showModal"> <p class="header">{{ otherText.title || title}}</p> <p class="body"> <slot></slot> </p> <p class="footer"> <p class="item success" id="sure" ref="sure" @click="makeSure" v-show="otherText.sureText || sureText">{{ otherText.sureText || sureText }}</p> <p class="item red" id="cancel" ref="cancel" @click="makeCancel" v-show="otherText.cancelText || cancelText">{{ otherText.cancelText || cancelText }}</p> </p> </p> </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 lang="scss" scoped> .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">
In fact, it can be written as<chat-modal :value="showModal" @input ="showModal = arguments[0]">
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

In Vue, v-model is an important instruction used to implement two-way binding. It allows us to easily synchronize user input to Vue's data attribute. But in some cases, we need to convert the data, such as converting the string type input by the user into a numeric type. In this case, we need to use the .number modifier of v-model to achieve this. Basic usage of v-model.number v-model.number is a modification of v-model

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

Vue is a popular front-end framework, and you often encounter various errors and problems when developing applications. Among them, Uncaught(inpromise)TypeError is a common error type. In this article, we will discuss its causes and solutions. What is Uncaught(inpromise)TypeError? Uncaught(inpromise)TypeError error usually appears in

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Using v-model's two-way binding in Vue to optimize application data performance In Vue, we often use the v-model directive to achieve two-way binding between form elements and data. This two-way binding greatly simplifies the development process and improves user experience. However, since v-model needs to listen to the input event of the form element, this two-way binding may cause certain performance problems when the amount of data is large. This article will introduce how to optimize data performance when using v-model and provide a

Vue error: v-model cannot be used correctly for two-way data binding. How to solve it? Introduction: Two-way data binding is a very common and powerful feature when developing with Vue. However, sometimes we may encounter a problem, that is, when we try to use v-model for two-way data binding, we encounter an error. This article describes the cause and solution of this problem, and provides a code example to demonstrate how to solve the problem. Problem Description: When we try to use v-model in Vue

How to solve Vue error: Unable to correctly use v-model for two-way data binding Introduction: Vue is a popular front-end framework that provides many convenient functions, including the v-model directive for implementing two-way data binding. However, sometimes we may encounter some errors when using v-model, especially when dealing with complex data structures. This article will introduce several common v-model errors and provide solutions and code examples. Error: Two-way binding of v-model and object properties

Solve Vue error: Unable to use v-model for two-way data binding. When developing with Vue, the v-model instruction is often used to achieve two-way data binding, but sometimes we encounter a problem when using v- An error will be reported when using the model, and two-way data binding cannot be performed correctly. This may be due to some common errors. Below I will introduce several common situations and corresponding solutions. The props attribute of the component is not set correctly. When we use the component, if we need to pass v-
