我已经创建了一个插件,但是我不知道如何创建一个基于Promise的插件。您能告诉我我需要在现有代码中添加什么吗?
我将vuetify js用于材料样式
NotifyDlg.vue:它包含用于警报或确认对话的对话代码。根据消息类型,我将显示/隐藏按钮
<template>
<v-dialog max-width="500px"
v-model='dialogue'>
<v-card>
<v-card-title primary-title>
<v-icon :color="messageType">{{messageType}}</v-icon>
<title>{{title}}</title>
</v-card-title>
<v-card-text>{{message}}</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn :color="messageType"
flat
v-if="confirmDlg"
@click="value=true">Yes</v-btn>
<v-btn :color="confirmDlg?'':'primary'"
flat
@click="value=false">{{getBtnText()}}</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<script>
export default {
props: {
confirmDlg: {
type: Boolean,
default: false
},
title: {
type: String,
default: '',
required: true
},
message: {
type: String,
default: '',
required: true
},
messageType: {
type: String,
default: 'warning',
required: true
}
},
data () {
return {
value: false,
dialogue:false
}
},
methods: {
getBtnText () {
if (this.confirmDlg) return 'No'
return 'Ok'
}
}
}
</script>
NotifyDlgPlugin.js:插件安装代码。然后将使用Vue.Use方法在main.js中调用此方法。
import NotifyDlg from './NotifyDlg.vue'
export default {
install: (Vue, options) => {
Vue.prototype.$notifyDlg = {
show (message, title, messageType, options = {}) {
options.message = message
options.title = title
options.messageType = messageType
}
}
}
}
从文档中,我仅了解可以在install方法中调用的全局函数。但是我不明白如何调用已创建的对话框,或者如何将真实或错误的值返回给被调用的方法。
对我的问题有任何建议吗?
答案 0 :(得分:2)
我想分享我基于诺言的对话代码:
import Dialog from "./Dialog.vue";
export function confirm(title, message) {
return new Promise((resolve, reject) => {
const dialog = new Vue({
methods: {
closeHandler(fn, arg) {
return function() {
fn(arg);
dialog.$destroy();
dialog.$el.remove();
};
}
},
render(h) {
return h(Dialog, {
props: {
title,
message,
},
on: {
confirm: this.closeHandler(resolve),
cancel: this.closeHandler(reject, new Error('canceled'))
}
});
}
}).$mount();
document.body.appendChild(dialog.$el);
});
}
这将创建对话框,将其添加到DOM并在对话框触发this.$emit('confirm')
事件时进行解析。