Vue.extend动态创建Toast

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>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值