使用vue封装的一个toast组件:
1.首先创建一个toast.vue页面:
<template>
<div class="toast" v-if="show">
{{text}}
</div>
</template>
<script>
export default {};
</script>
<style lang="less" scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
background: rgba(0, 0, 0, 0.35);
padding: 0.2rem;
border-radius: 0.1rem;
transform: translate(-50%, -50%);
color: #fff;
text-align: center;
font-size: 0.32rem;
}
</style>
2.创建一个index.js文件:
import vue from 'vue';
// toast组件
import toastComponent from './toast.vue'
// 返回一个 扩展实例构造器
const ToastConstructor = vue.extend(toastComponent)
// 定义弹出组件的函数 接收2个参数, 要显示的文本 和 显示时间
function showToast(text, duration = 1000) {
// 实例化一个 toast.vue
const toastDom = new ToastConstructor({
el: document.createElement('div'),
data() {
return {
text: text,
show: true
}
}
})
// 把 实例化的 toast.vue 添加到 body 里
document.body.appendChild(toastDom.$el)
// 过了 duration 时间后隐藏
setTimeout(() => { toastDom.show = false }, duration)
}
// 注册为全局组件的函数
function registryToast() {
// 将组件注册到 vue 的 原型链里去,
// 这样就可以在所有 vue 的实例里面使用 this.$toast()
vue.prototype.$toast = showToast
}
export default registryToast;
3.最后一步就是在main.js中将该组件注入到vue中:
import toastRegistry from './components/toast/index'
Vue.use(toastRegistry)
就可以在页面中以this.$toast()来使用了