createViewer
初始化一个 Viewer 实例,或复用传入的已有实例,并通过依赖注入暴露给当前组件及其后代组件。封装了手动 destroy() 和层层传参的样板代码:由元素创建的实例会在组件作用域结束时自动销毁。
Usage
vue
<script setup lang="ts">
import { createViewer } from 'vesium';
import { shallowRef } from 'vue';
import 'cesium/Build/Cesium/Widgets/widgets.css';
const elRef = shallowRef<HTMLElement>();
createViewer(elRef, {
// ... options
});
</script>
<template>
<div ref="elRef" class="inset-0 absolute" />
</template>注意
如果在同一个组件中使用 createViewer 和 useViewer,useViewer 应在 createViewer 之后调用,并优先使用当前组件创建的实例。
ts
import { createViewer, useViewer } from 'vesium';
import { shallowRef } from 'vue';
const elRef = shallowRef<HTMLElement>();
// 传入 DOM 元素(或 ref)创建新实例,组件卸载时自动销毁
const viewer = createViewer(elRef, { /* ...options */ });
// 传入已有实例只复用,不接管生命周期
const sharedViewer = createViewer(window.viewer);
const injectedViewer = useViewer();返回值
Readonly<ShallowRef<Viewer | undefined>>- 只读的Viewer引用;实例销毁后为undefined,与useViewer()指向同一个Viewer实例。
注意事项
- 通过
MutationObserver监听body:canvas被移出 DOM(如被v-if移除)时清空引用,避免继续使用失效实例。 - 元素 ref 尚未绑定时不会创建实例,元素出现后自动补建。
Type Definitions
typescript
import type { MaybeComputedElementRef } from '@vueuse/core';
import type { MaybeRef, ShallowRef } from 'vue';
import { Viewer } from 'cesium';
/**
* Pass in an existing Viewer instance,
* which can be accessed by the current component and its descendant components using {@link useViewer}
*
* When the Viewer instance referenced by this overloaded function becomes invalid, it will not trigger destruction.
* @param viewer - Existing viewer instance
* @returns The Viewer instance
*/
export declare function createViewer(viewer: MaybeRef<Viewer | undefined>): Readonly<ShallowRef<Viewer | undefined>>;
/**
* Initialize a Viewer instance, which can be accessed by the
* current component and its descendant components using {@link useViewer}.
*
* The Viewer instance created by this overloaded function will automatically be destroyed when it becomes invalid.
*
* @param element - The DOM element or ID that will contain the widget
* @param options - see `Viewer.ConstructorOptions`
* @returns The Viewer instance
*/
export declare function createViewer(element: MaybeComputedElementRef, options?: Viewer.ConstructorOptions): Readonly<ShallowRef<Viewer | undefined>>;