vue.extend实列(创建弹窗组件)

10 篇文章 0 订阅

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/>'
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值