>  기사  >  웹 프론트엔드  >  VUE2 이벤트 기반 팝업창 구현 예시

VUE2 이벤트 기반 팝업창 구현 예시

小云云
小云云원래의
2018-01-04 10:46:411671검색

이 글에서는 주로 VUE2에서 구현한 이벤트 기반 팝업창 예시를 소개하고 있는데, 에디터가 꽤 좋다고 생각해서 지금 공유하고 참고용으로 올려보겠습니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

며칠 전 vue에서 팝업 컴포넌트를 작성하는 방법을 알고 싶었습니다

두 가지 작성 방법이 있습니다.

1. 팝업 컴포넌트가 루트 컴포넌트에 배치되면, vuex를 사용하여 구성 요소의 표시 및 숨기기를 관리합니다. 컴포넌트에 배치하고 v-show 또는 v-if를 추가하여 제어합니다. 슬롯과 결합하여 다양한 요구에 맞는 팝업 창을 정의할 수 있습니다

2. 이벤트 관리는 팝업을 여는 글로벌 이벤트를 등록합니다. 창에 텍스트와 표시할 텍스트를 전달합니다. 관련 논리 제어를 약속과 결합하여 비동기 구현을 달성할 수 있습니다

confirme 및 propmt와 같은 이벤트 기반 팝업 창을 사용하는 것이 더 좋다고 생각합니다. 가장 좋은 방법은 약속 콜백을 사용하는 것입니다.

그래서 손이 가려워서 하나 썼습니다. 아래는 코드입니다.

propmt.js


import Vue from 'vue'
import promptComponent from './prompt.vue' // 引入弹窗的vue文件
const promptConstructor = Vue.extend(promptComponent); // 注册组件
let instance = new promptConstructor().$mount(''); // 获得组件的实例

document.body.appendChild(instance.$el); // 将组件的element插入到body中
const Alert = (text,okText)=>{
  if(instance.show === true) { //防止多次触发
    return;
  }
  // 为弹窗数据赋值
  instance.show = true; 
  instance.isAlert = true;
  instance.okText = okText||'确定';
  instance.message = text;
  //返回一个promise对象,并为按钮添加事件监听
  return new Promise(function(resolve,reject) {
    instance.$refs.okBtn.addEventListener('click',function() {
      instance.show = false;
      resolve(true);
    })
  })
};
const Confirm = (text,okText,cancelText)=>{
  if(instance.show === true) {
    return;
  }
  instance.show = true;
  instance.okText = okText||'确定';
  instance.cancelText = cancelText||'取消';
  instance.message = text;
  return new Promise(function(resolve,reject) {
    instance.$refs.cancelBtn.addEventListener('click',function() {
      instance.show = false;
      resolve(false);
    });
    instance.$refs.okBtn.addEventListener('click',function() {
      instance.show = false;
      resolve(true);
    })
  })
};
const Prompt = (text,okText,inputType, defaultValue)=>{
  if(instance.show === true) {
    return;
  }
  instance.show = true;
  instance.isPrompt = true;
  instance.okText = okText||'确定';
  instance.message = text;
  instance.inputType = inputType || 'text';
  instance.inputValue = defaultValue || '';
  return new Promise(function(resolve,reject) {
    instance.$refs.okBtn.addEventListener('click',function() {
      instance.show = false;
      resolve(instance.inputValue);
    })
  })
};

export {Alert,Confirm,Prompt}

prompt.vue


<style lang="less" scoped>
  .confirm-enter-active {
    transition: all .2s;
  }

  .confirm-leave-active {
    transition: opacity .2s;
  }

  .confirm-leave-to {
    opacity: 0;
  }

  .confirm-enter {
    opacity: 0;
  }

  .confirm {
    position: relative;
    font-family: PingFangSC-Regular;
    font-size: 17px;
    -webkit-user-select: none;
    user-select: none;
    // 遮罩层样式
    .masker {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, .4);
      -webkit-transition: opacity .1s linear;
      transition: opacity .1s linear;
      z-index: 100;
    }
    // 入库数据错误样式
    .box {
      position: absolute;
      top: 50%;
      left: 50%;
      width: 72%;
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
      text-align: center;
      border-radius: 12px;
      background-color: #fff;
      .message {
        height: 97px;
        line-height: 24px;
        font-family: PingFangSC-Regular;
        font-size: 17px;
        vertical-align: middle;
        color: #999;
        letter-spacing: -0.41px;
        p {
          margin: 20px auto 0 auto;
          vertical-align: middle;
        }
        &::after {
          content: &#39;&#39;;
          height: 100%;
        }
      }
      .prompt {
        margin: 20px 0;
        width: 100%;
        p {
          margin: 5px auto;
          font-size: 17px;
          line-height: 24px;
        }
        input {
          margin: 5px auto;
          border: 1px solid #333;
          border-radius: 6px;
          width: 100px;
          height: 30px;
          font-size: 14px;
          line-height: 20px;
          text-align: center;
        }
      }
      .button-group {
        a {
          width: calc(50% - 0.5px);
          text-align: center;
          font-size: 17px;
          line-height: 43px;
          color: blue;
        }
        .max-width {
          width: 100% !important;;
        }
      }
    }
  }
</style>
<template>
  <transition name="confirm">
    <p class="confirm" v-show="show">
      <p class="masker" @touchmove.prevent>
        <p class="box">
          <p class="message" v-if="!isPrompt">
            <p>{{message}}</p>
          </p>
          <p class="prompt" v-if="isPrompt">
            <p>{{message}}</p>
            <input type="text" v-model="inputValue" v-if="inputType === &#39;text&#39;" ref="inputEl">
            <input type="tel" v-model.number="inputValue" @keydown="enterCheck" v-if="inputType === &#39;tel&#39;" ref="inputEl">
          </p>
          <p class="button-group clearfix bd-top">
            <a class="bd-right fl" ref="cancelBtn" v-show="!isAlert && !isPrompt">{{cancelText}}</a>
            <a class="fr" ref="okBtn" :class="{&#39;max-width&#39;: isAlert || isPrompt}">{{okText}}</a>
          </p>
        </p>
      </p>
    </p>
  </transition>
</template>
<script type="text/ecmascript-6">
  import {mapState} from &#39;vuex&#39;
  export default{
    data() {
      return {
        show: false,
        message: &#39;请输入提示语&#39;,
        okText: &#39;确定&#39;,
        cancelText: &#39;取消&#39;,
        isAlert: false,
        isPrompt: false,
        inputValue: &#39;&#39;,
        inputType: &#39;&#39;
      }
    },
    methods: {
      // 金额输入框校验
      enterCheck(event) {
        // 只允许输入数字,删除键,11位数字
        if (event.keyCode === 46 || event.keyCode === 8) {
          return;
        }
        if (event.keyCode < 47 || event.keyCode > 58 || event.keyCode === 190) {
          event.returnValue = false;
        }
      },
    },
    watch: {
      show(){
        if (this.show) {
          this.$nextTick(() => {
            console.log(this.$refs.inputEl);
            console.log(this.inputType);
            this.$refs.inputEl.focus();
          });
        }
      }
    }
  }
</script>

main.js


import {Alert,Prompt,Confirm} from &#39;../lib/components/prompt/prompt.js&#39;

Vue.prototype.Alert = function(text,okText) {
  return Alert(text,okText)
};
Vue.prototype.Confirm = function(text,okText,cancelText) {
  return Confirm(text,okText,cancelText)
};
Vue.prototype.Prompt = function(text,okText,inputType, defaultValue) {
  return Prompt(text,okText,inputType, defaultValue)
};
component.vue:

inputName() {
  this.Prompt(&#39;请输入名称&#39;,&#39;确认&#39;,&#39;text&#39;).then(res =>{
    // do something use res
  });
},

관련 권장 사항:

jQuery로 팝업 효과를 만드는 방법

H5에서 webview를 사용하여 팝업창이 팝업되지 않는 문제를 해결하는 방법

PHP에서 js를 사용하여 팝업창에 매개변수를 전달하는 방법

위 내용은 VUE2 이벤트 기반 팝업창 구현 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.