1.效果
2.代码实现
目录结构
toast.js文件
import Vue from 'vue';
import Toast from '../components/Toast.vue'
const ToastConstructor=Vue.extend(Toast);//vue.extend创建构造器
console.log(ToastConstructor)
new Vue
function showToast(text,duration=4000){
//实例化构造器
const toastDOM=new ToastConstructor({
el:document.createElement('div'),//创建挂载元素
data(){
return{
text:text,
show:true
}
}
});
console.log(toastDOM);
document.body.appendChild(toastDOM.$el)//在body里添加元素
setTimeout(()=>{
toastDOM.show=false
},duration)
}
function toastRagistry(){
Vue.prototype.$toast=showToast;
}
export default toastRagistry;//导出
toast.vue
<template>
<div class="container" v-show="show">
<div>{{text}}</div>
</div>
</template>
<script>
export default {
name:'Toast',
data(){
return{
show:true,
text:'弹窗内容',
};
},
}
</script>
<style>
.container{
position: fixed;
width: 100px;
height: 40px;
text-align: center;
line-height: 40px;
color:#fff;
background-color: #f0f;
border-radius: 10px;
box-sizing: border-box;
}
</style>
App.vue
<template>
<div id="app">
<h1>使用vue.extend动态创建组件</h1>
<button @click="showToast">打开弹窗</button>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
showToast(){
this.$toast('弹窗内容');
}
}
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import toastRagistry from './api/toast.js'
Vue.config.productionTip = false
Vue.use(toastRagistry)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})