1.创建好一个Toast
比如创建一个toast.vue,代码如下:
<template>
<div class="container" v-if="show">
<div>{{ text }}</div>
</div>
</template>
<script>
export default {
name: 'Toast'
}
</script>
<style>
.container {
position: fixed;
top: calc(50% - 20px);
left: calc(50% - 50px);
width: 100px;
height: 40px;
text-align: center;
line-height: 40px;
color: #fff;
background-color: rgba(0, 0, 0, 0.8);
border-radius: 10px;
box-sizing: border-box;
}
</style>
2.使用toast.js来对组件进行动态的创建
import Vue from 'vue'
import Toast from './Toast.vue'
//通过Vue.extend创建出Toast对象的构造函数
const ToastConstructor = Vue.extend(Toast)
function showToast (text, delay = 2000) {
const toastDOM = new ToastConstructor({
el: document.createElement('div'),
data () {
return {
show: true,
text: text
}
}
})
//一般在页面的末尾将创建的对象插入
document.body.appendChild(toastDOM.$el)
//设置toast的消失时间
setTimeout(() => {
toastDOM.show = false
}, delay)
}
//将方法挂载在Vue上
function toastRegistry () {
Vue.prototype.$toast = showToast
}
export default toastRegistry
3.在main.js中引入
import toastRegistry from './extend/toast.js'
Vue.use(toastRegistry)
4.在需要使用的页面中定义方法使用
<template>
<div>
<h1>使用Vue.extend动态创建组件</h1>
<button @click="showToast">打开弹窗</button>
</div>
</template>
<script>
export default {
methods: {
showToast () {
this.$toast('开弹窗')
}
}
}
</script>