vue.extend() 动态创建组件
程序员文章站
2022-03-11 21:41:43
...
toast.js
import Toast from "./toast.vue";
import Vue from 'vue';
const ToastConstructor = Vue.extend(Toast);
function showToast(text, duration=2000) {
const toastDOM = new ToastConstructor({
el: document.createElement('div'),
data() {
return {
text: text,
show: true
}
}
});
document.body.appendChild(toastDOM.$el);
setTimeout(() => {
toastDOM.show = false;
}, duration)
}
function toastRegistry() {
Vue.prototype.$toast = showToast
}
export default toastRegistry;
toast.vue
<template>
<div v-if="show">
<div class="container" >{{ text }}</div>
</div>
</template>
<script>
export default {
name: "toast"
}
</script>
<style scoped>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 40px;
}
</style>
App.vue
<button @click="showToast">打开弹框</button>
methods: {
showToast() {
this.$toast("弹框")
}
}
效果: 显示弹框2秒后消失。
上一篇: [leetcode]344. 反转字符串
下一篇: Leetcode:344.反转字符串