一个vue2.x的简单插件开发实例
首先创建文件夹和文件
个人习惯把插件都放在src/plugins文件夹里
创建本次demo插件目录src/plugins/demo
以及目录文件
demo/index.js
demo/src/main.js
demo/src/main.vue
// index.js
import component from './src/main.js'
const install = function (Vue) {
// 注册全局组件
Vue.component(component.name, component)
// 添加全局API
Vue.prototype.$demo = component
}
export default install
// src/main.js
import Vue from 'vue'
import AlertComponent from './main.vue'
let instance;
// extend 是构造一个组件的语法器.传入参数,返回一个组件
let AlertConstructor = Vue.extend(AlertComponent);
let initInstance = () => {
// 实例化ConfirmConstructor组件
instance = new AlertConstructor({
el: document.createElement('div')
});
// 添加到boby
document.body.appendChild(instance.$el);
}
let component = (options = {}) => {
// 初始化
initInstance();
instance.$data.title = options.title
// 返回Promise
return new Promise((resolve, reject) => {
console.log(instance)
console.log(options)
instance.show = true;
let onSelect = instance.onSelect;
let onCancel = instance.onCancel;
instance.onSelect = () => {
let id = instance.id
// 先执行instance.onSelect(main.vue里面的onSelect函数)
onSelect();
// 再执行自定义函数
resolve(id);
}
instance.onCancel = () => {
// 先执行instance.onCancel(main.vue里面的onCancel函数)
onCancel();
// 再执行自定义函数
reject(new Error('取消'));
}
});
}
export default component;
// main.vue
<template>
<div class="modal">
<Button type="primary" icon="md-add" @click="onSelect">选择</Button>
<Button type="primary" icon="md-add" @click="onCancel">取消</Button>
<Button type="primary" icon="md-add" @click="onEdit">修改</Button>
</div>
</transition>
<script>
export default {
data () {
return {
title: '实例',
id: 11101\
}
},
methods: {
onSelect () {
console.log('选择了')
},
onCancel () {
console.log('取消了')
},
onEdit () {
console.log('修改了')
this.id = 11
}
}
}
</script>
<style lang="less" scoped>
.modal {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
/*height: 100vh;*/
/*width: 100vw;*/
background-color: rgba(0, 0, 0, 0.2);
display: flex;
justify-content: center;
align-items: center;
z-index: 99;
}
</style>
最后在根src目录下的main.js中引入插件
// main.js
import demo from '@/plugins/demo';
Vue.use(demo);
然后就可以在别的地方愉快的调用了
this.$demo({ title: '获取' }).then(res => {
console.log('res', res)
}).catch(e => {
console.log('“取消了”', e)
})
|