VUE2实现事件驱动弹窗示例
前几天想了解vue如何写弹窗组件

创新互联建站是一家专业提供铜陵企业网站建设,专注与成都做网站、网站制作、HTML5建站、小程序制作等业务。10年已为铜陵众多企业、政府机构等服务。创新互联专业的建站公司优惠进行中。
有以下两种可取的写法:
1.状态管理 如果弹窗组件放在根组件,使用vuex来管理组件的show和hide。放在组件内,通过增加v-show或v-if来控制,可结合slot,定义不同需求的弹窗
2.事件管理 注册一个全局事件来打开弹窗,传入需展示的文字和相关的逻辑控制,可结合promise,实现异步
觉得对用像confirme和propmt这类弹窗,还是事件驱动的好。最好就是能使用promise回调。
于是手痒就写了一个。下面是代码。
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
{{message}}
main.js
import {Alert,Prompt,Confirm} from '../lib/components/prompt/prompt.js'
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('请输入名称','确认','text').then(res =>{
// do something use res
});
},
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
名称栏目:VUE2实现事件驱动弹窗示例
网站链接:http://www.lzwzjz.cn/article/jgpjjh.html


咨询
建站咨询
