vue2和vue3中 封装组件 通过函数调用

1、vue2

Toast 组件:

<template>
  <transition name="fade">
    <div
      v-show="show"
      class="my-toast"
      @touchmove.prevent>
      <div class="mask" @click="onClose"></div>
      <div class="content">
        {{ content }}
      </div>
    </div>
  </transition>
</template>
export default {
  data () {
    return {
      show: false,
      content: ''
    }
  },
  methods: {
    onClose () {
      this.show = false
    }
  }
}

Toast.js

import Vue from 'vue'
import Toast from './myToast'

const toastConstructor = Vue.extend(Toast)

// 定义弹出组件的函数 接收2个参数, 要显示的文本 和 显示时间
function myToast (text, duration = 5000) {

  // 实例化一个 toast.vue
  const toast = new toastConstructor()
  // 将组件对象手动挂载到某一个元素上
  toast.$mount(document.createElement('div'))
  // toast.$el对应的就是DIV
  document.body.appendChild(toast.$el)

  toast.content = text
  toast.show = true
  setTimeout(() => {
    toast.show = false
  }, duration)

}

export default myToast

使用:

<template>
	<div>
		<button @click="configClcik"></button>
	<div>
</template>

<script>
import myToast from 'components/myToast'

methods: {
	configClcik() {
		myToast('弹出信息')
	}
}
</script>

vue3

Toast 组件

<template>
  <transition name="toast">
    <div v-show="show" class="toast">{{ message }}</div>
  </transition>
</template>

<script setup>
import {ref, unref} from "vue";
 
const show = ref(false)
const message = ref('')

const close = () => {
  show.value = false
}

const open = (message, delay = 1000) => {
  if (show.value) return
  message.value = message
  show.value = true
  setTimeout(close, unref(delay))
}

defineExpose({open, close})
</script>

Toast.js

import {render, createVNode, VNode} from 'vue'
import Toast from './Toast.vue'

const createToast = () => {
    const _vm = createVNode(Toast)
    const container = document.createElement('div')
    render(_vm, container)
    document.body.appendChild(container)
    return _vm
}
 
let toast = null
export const useToast = () => {
    if (!toast) toast = createToast()
 
    const toast = (message: string) => {
        toast?.component?.exposed?.open(message)
    }
 
    return toast
}

使用

<template>
  <button @click="toast('hello world')">button</button>
</template>

<script setup>
import useToast from "@/components/Toast";
 
const toast = useToast()
 
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值