|
| 1 | +<template> |
| 2 | + <div> |
| 3 | + <component :is="showComponent" /> |
| 4 | + </div> |
| 5 | +</template> |
| 6 | + |
| 7 | +<script setup lang="tsx"> |
| 8 | +import { shallowRef, onMounted, onBeforeUnmount } from 'vue' |
| 9 | +import { TinyLoading } from '@opentiny/vue-mobile' |
| 10 | +import { vueComponents } from '@/views/components/cmp-config' |
| 11 | +
|
| 12 | +const showComponent = shallowRef(null) |
| 13 | +const notFoundDemo = (demoPath) => <div>{`${demoPath}示例资源不存在,请检查文件名是否正确?`}</div> |
| 14 | +const getComponent = async (demoPath) => { |
| 15 | + if (vueComponents[demoPath]) { |
| 16 | + const cmp = (await vueComponents[demoPath]()).default |
| 17 | + return cmp |
| 18 | + } else { |
| 19 | + return notFoundDemo(demoPath) |
| 20 | + } |
| 21 | +} |
| 22 | +
|
| 23 | +let loadingService |
| 24 | +const showLoading = () => { |
| 25 | + if (!loadingService) { |
| 26 | + loadingService = TinyLoading.service({ |
| 27 | + lock: true |
| 28 | + }) |
| 29 | + } |
| 30 | +} |
| 31 | +const closeLoading = () => { |
| 32 | + if (loadingService) { |
| 33 | + loadingService.close() |
| 34 | + loadingService = null |
| 35 | + } |
| 36 | +} |
| 37 | +
|
| 38 | +const receiveMessage = ({ data }) => { |
| 39 | + const { from, component, demo } = data || {} |
| 40 | + if (!['tiny-vue-site'].includes(from)) { |
| 41 | + return |
| 42 | + } |
| 43 | + showLoading() |
| 44 | + const demoPath = `${component}/${demo}` |
| 45 | + getComponent(demoPath).then((cmp) => { |
| 46 | + showComponent.value = cmp |
| 47 | + closeLoading() |
| 48 | + }) |
| 49 | +} |
| 50 | +
|
| 51 | +onMounted(() => { |
| 52 | + const searchObj = new URLSearchParams(location.search) |
| 53 | + const component = searchObj.get('component') |
| 54 | + const demo = searchObj.get('demo') |
| 55 | + window.addEventListener('message', receiveMessage, false) |
| 56 | + if (component && demo) { |
| 57 | + showLoading() |
| 58 | + const demoPath = `${component}/${demo}` |
| 59 | + getComponent(demoPath).then((cmp) => { |
| 60 | + showComponent.value = cmp |
| 61 | + closeLoading() |
| 62 | + }) |
| 63 | + } |
| 64 | +}) |
| 65 | +
|
| 66 | +onBeforeUnmount(() => { |
| 67 | + window.removeEventListener('message', receiveMessage) |
| 68 | +}) |
| 69 | +</script> |
| 70 | + |
| 71 | +<style> |
| 72 | +html, |
| 73 | +body { |
| 74 | + margin: 0; |
| 75 | + padding: 0; |
| 76 | +} |
| 77 | +</style> |
0 commit comments