插件介绍
自定义一个可以接受数据的模板用作mseage的弹窗组件,比如点击一个按钮会出现这种提示的组件。
将这个组件变为一个插件,可以通过类似$store
来使用的插件。
比如在某个组件调用这个插件可以使用$toast.show(mesage,timeout)
的方式使用。
要完成这个功能需要用到vue的extend和use的方法。
插件实施完整步骤
创建对应弹窗模板
<template>
<div class="toast"
v-show="isShow">
{{message}}
</div>
</template>
<script>
export default {
name: 'Toast',
data () {
return {
message: '',
isShow: false // 默认为不显示弹窗
}
},
methods: {
// 定义一个方法,这样子可以通过.show的方式来调养这个方法,方法接收两个参数,弹窗内容和消失时间
show (message, time = 1500) {
// 如果调用了这个方法,就将isShow变成true,也就是显示弹窗
this.isShow = true
// 显示弹窗信息
this.message = message
// 做一个定时器,定时器的作用就是让弹窗显示一段时间后消失,也就是将isShow 和message在前面的存储的状态还原最初
setTimeout(() => {
this.isShow = false
this.message = ''
// 传入的显示时间
}, time)
}
},
}
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
}
</style>
创建将toastt组件上的html页面挂载到需要用到$toast的页面上,也就是一个js文件
// 导入刚才创建好的组件
import Toast from './Toast'
//Vue.use(toast),使用use方法会执行install,在这里创建一个空对象
const obj = {}
obj.install = function (Vue) {
// console.log('一开始就执行了install', Vue)
// 1.创建组件构造器
const toastContrustor = Vue.extend(Toast)
// 2.new方式根据组件构造器,可以创建出来一个组件对象
const toast = new toastContrustor()
// 3. 将组件对象手动挂载到某一个元素里面
toast.$mount(document.createElement('div'))
// 4.toast.$el对应的就是div
document.body.appendChild(toast.$el)
// 1-4步的作用是将Toast组件上的html页面挂载到需要用到$toast的页面上
// 使用prototype将这个toast赋予成为vue的实例
Vue.prototype.$toast = toast
}
// 导出这个obj
export default obj
将toast挂载到vue上面,在main.js上进行
import Vue from 'vue'
import App from './App.vue'
// 导入刚才写好的index.js
import toast from 'components/common/toast/index.js'
Vue.config.productionTip = false
// 安装toast插件
Vue.use(toast)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
在一个界面上使用自定义好的插件
<template>
<div class="home">
<button @click="click">按钮</button>
</div>
</template>
<script>
export default {
name: 'home',
data () {
return {
}
},
methods: {
click () {
this.$toast.show('弹出的消息', 1500)
}
}
}
</script>
<style scoped>
.wrapper {
height: 150px;
background: red;
}
</style>
效果:
至此完成自定义message消息弹窗插件(toast)的功能。