弹窗组件在vue中应用很广,今天我就来给大家分享一下怎么封装的?
首先,先建一个文件夹,在src/components下建立一个toast文件夹,里面放两个文件,一个是index.js,一个是toast.vue
以下是index.js里面的代码
import Toast from './Toast'
//创建obj对象
const obj ={}
//当main.js执行就好触发以下函数
obj.install = function(Vue){
//1.创建组件构造器
const toastConstrustor = Vue.extend(Toast);
//2.new的方式,根据组件构造器,可以创建出来一个组件对象
const toast = new toastConstrustor();
//3.将组件对象,手动挂载到某一个元素上
toast.$mount(document.createElement('div'))
//4.toast.$el对应的就是div
document.body.appendChild(toast.$el)
Vue.prototype.$toast = toast;
}
//导出obj对象
export default obj
这是toast.vue里面的代码
<template>
<div class="toast">
<div v-show="isShow">{{message}}</div>
</div>
</template>
<script>
export default {
name: "Toast",
methods: {
show(message="信息",duration=1500) {
this.show = true,
this.message = message
setTimeout(() =>{
this.isShow = false;
this.message = ''
},duration)
}
},
}
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
color: #fff;
padding: 8px 10px;
transform: translate(-50%,-50%);
background-color: rgba(0,0,0,0.2);
z-index: 999;
}
</style>
好了,封装完成在home.vue里面可以试试喽
<template>
<div id="app">
<input type="button" value="显示弹窗" @click="showToast">
</div>
</template>
<script>
export default {
methods: {
showToast () {
this.$toast('我是弹出消息')
}
}
}
</script>
总结:
vue.extend可以vue.extend 函数可以生成一个 组件构造器 可以用这个函数构造出一个 vue组件实例
document.body.appendChild() 可以动态的把组件加到 body里面去
转载:https://blog.csdn.net/weixin_44340914/article/details/106738672
查看评论