Open zhaobinglong opened 4 years ago
|-plugins
<template>
<div id="toast">
<div>加载中{{ message }}</div>
</div>
</template>
<style>
// 样式文件写在这里
</style>
<script>
export default {
props: {
message: {
type: String,
default: ''
}
},
}
</script>
// toast.js
var Toast = {};
Toast.install = function (Vue, options) {
Vue.prototype.$toast = (tips) => {
let toastTpl = Vue.extend(Toast.vue);
let tpl = new toastTpl().$mount().$el; // 2、创建实例,挂载到文档以后的地方
document.body.appendChild(tpl); // 3、把创建的实例添加到body中
setTimeout(function () { // 4、延迟2.5秒后移除该提示
document.body.removeChild(tpl);
}, 2500)
}
}
module.exports = Toast;
import Toast from '@/components/Toast/toast.js'
...
Toast({
message:"123"
});
...
import Vue from 'vue';
import Toast from './toast.vue'
let Toast = (options = {}) => {
let ToastConstructor = Vue.extend(Toast);
let instance = new ToastConstructor({
el: document.createElement('div')
});
// 此处为传递到toast.vue里面props的值
instance.message='123';
document.body.appendChild(instance.$el);
}
export default {
install: function(Vue){
Vue.$toast = Vue.prototype.$toast = Toast;
}
}
import Toast from '@/components/Toast/toast.js'
Vue.use(Toast);
this.$toast()
https://juejin.cn/post/6905409280761921543 https://github.com/MeForma/vue-toaster, 一个基于vue3的toast插件 https://juejin.cn/post/6916362519279829005
setup() {
const { ctx } = getCurrentInstance();
const showMessage = () => {
ctx.$message.success("this is message");
};
return {
showMessage
};
}
// 有时候在调用插件的时候,希望传递一些回调函数,比如获取插件中用户输入的内容等等
import template from "./index.vue";
const input = {};
input.install = (Vue) => {
// 扩展 vue 插件
const ToastCon = Vue.extend(template);
// 挂载 dom, 添加到 body 后面
const instance = new ToastCon()
instance.$mount(document.createElement("div"));
document.body.appendChild(instance.$el);
// 给 vue 原型添加 toast 方法
Vue.prototype.$input = ({title, success, cancel}) => {
instance.visible = true;
instance.title = title;
// 传递两个回调函数,一个成功的回调,一个失败的回调
if (typeof success !== "undefined") {
instance.success = success;
}
if (typeof cancel !== "undefined") {
instance.cancel = cancel;
}
};
};
export default input;
export default {
data() {
return {
visible: false,
title: "",
cont: "",
};
},
// 在页面中准备好这两个回调函数
props: {
success: {
type: Function,
},
cancel: {
type: Function,
},
},
methods: {
onOk() {
this.visible = false;
console.log(this.cont);
this.success(this.cont);
},
},
};
应用场景
插件和组件的区别
插件通常会为 Vue 添加全局功能。所谓全局,即不需要像组件那样,每次使用他前都需要先引入一次。对于插件只要在最开始引入一次插件是对vue框架功能的增强,比如说vuex插件,router插件,而组件是针对业务逻辑而开发的公共的模块
插件通用模板
在main中全局导入插件
参考
https://blog.csdn.net/weixin_42207975/article/details/107313106