首先既然是插件,我的理解就是只需要调用传值即可实现,想toast这么常用的插件我们不可能每一个组件都引用文件(不管是js还是vue文件)都是多余!
首先,我们需要创建一个toast.vue的模版组件内容如下:
<template> <div v-show="visible" class="toast"> <i>{{ message }}</i> </div></template><script>export default { name: 'toast', data () { return { message: '', visible: true } }}</script><style lang="css"> .toast { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%) scale(1); word-wrap: bread-word; text-align: center; z-index: 888; max-width: 80%; color: #fff; border-radius: 20px; padding: 30px 34px; background: rgba(0, 0, 0, 0.7); overflow: hidden; }</style>
组件很简单,就是使用vue的数据绑定,默认显示toast内容
下面我们就要正式写vue的插件了,请注意,前方高能
import toast from './Toast.vue'
let Toast = []Toast.install = (Vue, option = {}) => { const ToastTem = Vue.extend(toast) let removeDom = event => { if (event.target.parentNode.childNodes.length > 1) { event.target.parentNode.removeChild(event.target) } else { event.target.parentNode.parentNode.removeChild(event.target.parentNode) } } ToastTem.prototype.close = function () { this.visible = false this.$el.addEventListener('transitionend', removeDom) } Vue.prototype.$toast = (option) => { var instance = new ToastTem().$mount(document.createElement('div')) let duration = option.duration || 3000 instance.message = typeof option === 'string' ? option : option.message document.body.appendChild(instance.$el) setTimeout(function () { instance.close() }, duration) }}export default Toast
接下来,你就可以在入口文件进行使用刚刚开发的插件啦!
toast用法:
import Vue from 'vue'import App from './App.vue'import router from './router'import store from './store'import Toast from './plugins/toast'Vue.use(Toast)Vue.config.productionTip = falsenew Vue({ router, store, render: h => h(App)}).$mount('#app')
好了,toast插件写完了,可以在任何组件中直接用this.$toast()
是不是很方便!
如有问题,欢迎大家指正缺陷!如果喜欢请留下你的脚步!!!!
原文地址: ithack.github.io/