Home > Web Front-end > JS Tutorial > How to use v-model and promise to implement vue pop-up component

How to use v-model and promise to implement vue pop-up component

php中世界最好的语言
Release: 2018-05-28 15:00:30
Original
2117 people have browsed it

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() {}//点击取消的回调
}
Copy after login

Promise callback method

<chat-modal ref="chat-modal"></chat-modal>
methods: {
  display() {
    this.$refs["chat-modal"].openModal({
      title: "弹窗标题",
      sureText: "确认",
      cancelText: "取消"
    }).then(res => {
      //点击确认的回调
    }, res => {
      //点击取消的回调
    })
  }
}
Copy after login

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="{&#39;smSize&#39;: 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>
Copy after login

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);
    }
Copy after login

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)),
Copy after login

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("点击了确定");
});
Copy after login

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("点击了取消");
});
Copy after login

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;
Copy after login

将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();
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何使用Vue内父子组件通讯todolist组件

如何使用Vue整合AdminLTE模板

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template