函数式调用组件

597 阅读1分钟

1.vue3.0创建一个组件 导出 hide 和 show 函数

export default defineComponent({
		setup(props, context) {
			const message = ref('')
			const mType = ref<MessageType>('default')
			
						
			const classObject = computed(() => {
				return {
				    'alert-success': mType.value === 'success',
				    'alert-danger': mType.value === 'error',
				    'alert-primary': mType.value === 'default'
				}
			}) 
			
			
			
			const isVisible = ref(false)
			
			const hide = () => {
				isVisible.value = false
			}
			
			const show = (sMessage: string, type: MessageType) => {
				message.value = sMessage
				mType.value = type
				isVisible.value = true
			}
			
			return {
				isVisible,
				message,
				classObject,
				hide,
				show
			}

		}
	}) 

2.创建ts

createApp 创建组件

mount挂载到自己创建的节点上

messageIntance._instance.proxy.show 和 messageIntance._instance.proxy.hide 取出组件内部的函数 并执行

调用方式 createMessage('this is a error', 'error')

import {createApp} from 'vue'
import Message from '../components/Message.vue'


		const messageIntance = createApp(Message)
		const messageNode = document.createElement('div')
		document.body.appendChild(messageNode)
		messageIntance.mount(messageNode)

  
export type MessageType = 'success' | 'error' | 'default'

const createMessage = (message: string, type: MessageType, timeout: number = 2) => {
	
	  const inst: any = messageIntance._instance
	  if (inst.proxy) {
	  	inst.proxy.show(message, type)
	  }
	  setTimeout(() => {
		  if (inst.proxy) {
			  inst.proxy.hide()
		  }
	  }, timeout * 1000)
  
}

export default createMessage