>  기사  >  웹 프론트엔드  >  vue.js는 MessageBox 구성 요소에 대한 전역 호출을 구현합니다.

vue.js는 MessageBox 구성 요소에 대한 전역 호출을 구현합니다.

小云云
小云云원래의
2017-12-12 11:52:103064검색

Vue.js 구성 요소에 대한 많은 지식 포인트가 있으며 매우 중요합니다. 이 기사에서는 vue.js를 사용하여 전역 호출을 구현하는 MessageBox 구성 요소를 개발하는 것과 관련된 정보를 자세히 소개합니다. 샘플 코드를 통해 필요한 친구들이 참고할 수 있도록 아래 내용을 살펴보도록 하겠습니다. 모두에게 도움이 되기를 바랍니다.

컴포넌트 템플릿

// /src/components/MessageBox/index.vue
<template>
 <p class="message-box" v-show="isShowMessageBox">
  <p class="mask" @click="cancel"></p>
  <p class="message-content">
  <svg class="icon" aria-hidden="true" @click="cancel">
   <use xlink:href="#icon-delete" rel="external nofollow" ></use>
  </svg>
   <h3 class="title">{{ title }}</h3>
   <p class="content">{{ content }}</p>
  <p>
   <input type="text" v-model="inputValue" v-if="isShowInput" ref="input">
  </p>
   <p class="btn-group">
    <button class="btn-default" @click="cancel" v-show="isShowCancelBtn">{{ cancelBtnText }}</button>
    <button class="btn-primary btn-confirm" @click="confirm" v-show="isShowConfimrBtn">{{ confirmBtnText }}</button>
   </p>
  </p>
 </p>
 </template>
 
 <script>
 export default {
  props: {
  title: {
   type: String,
   default: '标题'
  },
  content: {
   type: String,
   default: '这是弹框内容'
  },
  isShowInput: false,
  inputValue: '',
  isShowCancelBtn: {
   type: Boolean,
   default: true
  },
  isShowConfimrBtn: {
   type: Boolean,
   default: true
  },
  cancelBtnText: {
   type: String,
   default: '取消'
  },
  confirmBtnText: {
   type: String,
   default: '确定'
  }
  },
  data () {
  return {
   isShowMessageBox: false,
   resolve: '',
   reject: '',
   promise: '' // 保存promise对象
  };
  },
  methods: {
  // 确定,将promise断定为resolve状态
  confirm: function () {
   this.isShowMessageBox = false;
   if (this.isShowInput) {
   this.resolve(this.inputValue);
   } else {
   this.resolve('confirm');
   }
   this.remove();
  },
  // 取消,将promise断定为reject状态
  cancel: function () {
   this.isShowMessageBox = false;
   this.reject('cancel');
   this.remove();
  },
  // 弹出messageBox,并创建promise对象
  showMsgBox: function () {
   this.isShowMessageBox = true;
   this.promise = new Promise((resolve, reject) => {
   this.resolve = resolve;
   this.reject = reject;
   });
   // 返回promise对象
   return this.promise;
  },
  remove: function () {
   setTimeout(() => {
   this.destroy();
   }, 300);
  },
  destroy: function () {
   this.$destroy();
   document.body.removeChild(this.$el);
  }
  }
 };
 </script>
 <style lang="scss" scoped>
 // 此处省略 ...
 </style>

컴포넌트에 전역 기능 추가

vue.js 공식 문서에는 플러그인 개발에 대한 소개가 있습니다. 구체적인 구현 코드는 다음과 같습니다.

// /src/components/MessageBox/index.js

import msgboxVue from './index.vue'; 
// 定义插件对象
const MessageBox = {};
// vue的install方法,用于定义vue插件
MessageBox.install = function (Vue, options) {
 const MessageBoxInstance = Vue.extend(msgboxVue);
 let currentMsg, instance;
 const initInstance = () => {
 // 实例化vue实例
 currentMsg = new MessageBoxInstance();
 let msgBoxEl = currentMsg.$mount().$el;
 document.body.appendChild(msgBoxEl);
 };
 // 在Vue的原型上添加实例方法,以全局调用
 Vue.prototype.$msgBox = {
 showMsgBox (options) {
  if (!instance) {
  initInstance();
  }
  if (typeof options === 'string') {
  currentMsg.content = options;
  } else if (typeof options === 'object') {
  Object.assign(currentMsg, options);
  }
  return currentMsg.showMsgBox();
 }
 };
};
export default MessageBox;

Global use

// src/main.js
import MessageBox from './components/MessageBox/index';
Vue.use(MessageBox);

Page call

앞서 정의한 방법을 따르면 각 페이지에서 이 컴포넌트를 즐겁게 호출할 수 있습니다.

this.$msgBox.showMsgBox({
 title: '添加分类',
 content: '请填写分类名称',
 isShowInput: true
}).then(async (val) => {
 // ...  
}).catch(() => {
 // ...
});

마지막으로 렌더링이 있습니다.


모두가 Vue.js 구성 요소 지식을 더 명확하게 파악하고 빠르게 작동을 시작할 수 있기를 바랍니다.

관련 권장 사항:

Vue.js 구성 요소란 무엇인가요? Vue.js 구성 요소 사용 요약

Vue.js 구성 요소 및 구성 요소 통신에 대한 심층 토론

C# 메시지 상자 messagebox 사용 소개

위 내용은 vue.js는 MessageBox 구성 요소에 대한 전역 호출을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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