Vue Three.js 新玩法之 TresJs

效果预览

今天我们将会探索一个名为 TresJs 的工具,它是一个使得在 Vue3 中使用 Three.js 变得更加容易的库。下面,我们将会使用 TresJs 来创建一个如下 iframe 展示的简单的 3D 手机模型展示。

什么是 TresJs?

TresJS是一个声明性的3D场景构建工具,它允许你像使用Vue组件一样构建3D场景。TresJS利用Vite提供的热模块替换(HMR)功能,无论应用程序的大小如何,它都能保持快速的加载速度。此外,TresJS始终保持最新的Three.JS特性,让你可以随时使用ThreeJS的所有更新功能。通过扩展核心功能,例如使用cientos和postprocessing等包,或者添加你自己的包,你可以更好地使用Three.JS的生态系统。总的来说,无论你是在创建3D手机模型展示,还是在进行其他类型的3D项目,TresJS都能为你提供极大的便利。

一些基本概念

在 Three.js 中,我们需要 4 个核心元素来创建 3D 体验,分别是:Scene、Renderer、Camera 和 Object

Scene

在Three.js中,Scene(场景)是所有物体和光源的容器,它表示了一个三维的空间环境。你可以将其看作是一个舞台,所有的物体,包括几何体、灯光、摄像机等都在这个舞台上。在创建任何Three.js应用时,我们都需要先创建一个Scene。在这个场景中,我们可以添加或删除物体,调整物体的位置、旋转和缩放等属性,也可以添加各种光源来影响物体的渲染效果。最后,我们会使用一个摄像机来决定从哪个角度查看这个场景,然后将场景渲染到一个二维的屏幕上。

在 TresJS 中,Scene 由组件 TresCanvas 提供。

Renderer

在 Three.js 中,Renderer 是一个非常重要的组件。它负责将你的场景渲染到屏幕上。你可以把它想象成一个画家,它的任务是把你的 3D 场景画出来。

Three.js 提供了多种 Renderer,包括 WebGLRenderer、WebGL1Renderer、CSS2DRenderer、CSS3DRenderer 等。其中,WebGLRenderer 是最常用的 Renderer,它使用 WebGL 技术来渲染 3D 场景。

在 TresJS 中,Renderer 在组件 TresCanvas 初始化时会自动创建。

Camera

在 Three.js 中,摄像机是创建 3D 场景的重要组件。摄像机定义了我们观察 3D 场景的视角和视野。Three.js 提供了多种类型的摄像机,但最常用的是透视摄像机(PerspectiveCamera)和正交摄像机(OrthographicCamera)。

透视摄像机(PerspectiveCamera)模拟了人眼看到的视觉效果,即远处的物体比近处的物体看起来小。它的参数包括视野角度、长宽比以及近裁剪面和远裁剪面。

正交摄像机(OrthographicCamera)则不考虑深度,无论物体离摄像机的距离如何,其大小始终保持一致。这种摄像机常用于创建 2D 效果或者工程图表。

在我们的 Vue.js 3D 手机模型展示中,我们使用了透视摄像机(TresPerspectiveCamera)来创建更为真实的 3D 视觉效果。

在 TresJS 中,Camera 由组件 TresPerspectiveCamera 提供。

Object

在 Three.js 中,Object 指的是 添加在场景中被观测的物体。 在实际开发中,分为手敲的 Mesh 和 从外部导入的模型文件。

在 Three.js 中,Mesh 是一个基本的3D物体,它由一个几何体和一个材质组成。几何体是一个定义了物体形状的对象,材质则是定义了物体表面的外观。在一个Mesh中,几何体和材质的结合就形成了一个可以在场景中渲染的3D物体。

而从外部导入的模型文件,由于其格式有非常多种,加载方式各不相同,具体的可以查看 TresJS 或 Three.js 的官方文档。

开始使用

我们的目标是在 Vue.js 中创建一个 3D 手机模型展示。首先,我们需要在 Vue.js 组件中设置场景。

在我们的 Index.vue 文件中,我们首先导入了必要的 TresJs 组件和函数,包括 TresLeches,TresCanvas 和 useControls。然后,我们在模板中设置了一个 TresCanvas,并在其中添加了一些基础的 Three.js 元素,如 TresPerspectiveCamera,OrbitControls,TresDirectionalLight 和 TresAmbientLight。

我们还使用了 useControls 函数来创建一些控制元素,如背景颜色,方向光颜色,方向光强度和环境光强度。这些控制元素可以让我们在运行时动态调整这些属性。

<template>
	<div class="container-i">
		<TresLeches abs />
		<TresCanvas :clear-color="bgColor.value">
			<TresPerspectiveCamera :position="[2, 0, 3]" :look-at="[0, 0, 0]" />
			<OrbitControls />
			<TresDirectionalLight :color="color.value" :position="[3, 3, 3]"
				:intensity="directionalLightIntensity.value" />
			<TresAmbientLight :intensity="ambientLightIntensity.value" />
			<Suspense>
				<Phone />
			</Suspense>
		</TresCanvas>
	</div>
</template>

可见,不同于 Three.js,TresJs 提供了一种更加声明式的方式来创建 3D 场景。通过使用 TresJs,我们可以在 Vue.js 中更加方便地创建 3D 场景,并且可以使用 Vue.js 的响应式数据来动态调整场景中的元素。

加载3D模型

接下来,我们需要加载我们的 3D 手机模型。在 Phone.vue 文件中,我们使用 useGLTF 函数来加载我们的模型。然后,我们获取模型的边界框,并计算出其大小和中心点。最后,我们将模型的位置调整到原点,并根据其大小调整其缩放。

<template>
    <primitive :object="model"></primitive>
</template>
<script setup lang="ts">
import * as THREE from 'three'
import { useGLTF } from '@tresjs/cientos'

const { scene: model } = await useGLTF(new URL('/models/scene.gltf',import.meta.url).href)

const box = new THREE.Box3().setFromObject(model);
const size = box.getSize(new THREE.Vector3()).length();
const center = box.getCenter(new THREE.Vector3());

// 移动模型到原点
model.position.x += (model.position.x - center.x);
model.position.y += (model.position.y - center.y) + 0.5;
model.position.z += (model.position.z - center.z);

// 调整模型大小
const scale = 2 / size;
model.scale.set(scale, scale, scale);
</script>

结论

TresJs 提供了一种在 Vue.js 中使用 Three.js 的简洁方式,使得我们可以在 Vue.js 中方便地使用 Three.js 的各种功能。目前此项目在 github 上已经有 1k+ 的 star,期待其官方文档的完善,以及更多的开发者加入到这个项目中,共同推动 Three.js 在 Vue.js 中的发展。

结合GreenSock实现数字翻牌效果

引言

  好久没更新博客了,最近得空把githubPage挂到了cloudflare的CDN上(别问我为什么,问就是他免费且我穷)。顺便写一篇文章,测试测试速度。

  最近在做一个项目,需要实现一个数字翻牌的效果。于是就想到使用 GreenSock 这个库。GreenSock 是一个强大的动画库,可以实现很多复杂的动画效果,而且它的 API 也非常丰富,所以就用它来实现了这个数字翻牌的效果。

实现效果

数字翻牌效果

思路解析

设计思路

  1. 视图结构
      可以看见,我们希望实现的效果是中间状态(如从 0->9)的多层翻牌效果。为了便于理解,我这里先使用只有一个中间过程的情况来进行分析。
    正面 反面

  上面两张图分别展示了从0翻动至1的结束状态过程。可以看到,从0翻至1,其视图主要分为 2 个主要部分,即底部和顶部(可以想象一下翻书的 3d 模型)。

  底部的上半部分为1的上半部分,下半部分则为0的下半部分。

  顶部则可以想象为一个具有正反面的 50%高度卡片,并互相叠在一起。设中间的断口为旋转轴,则中间部分(顶部)的正反面分别是0的上半部分和1的下半部分。

  1. 动画思路
      想象一下翻牌的过程,可以知道底部是不需要做动画的。需要做动画的只有中间的顶部部分,即顶部的正反面在翻牌过程中需要做动画。从初始的0翻至1的过程中,顶部的正反面需要做同步动画,即从上部以中间空隙为 X 轴,向下翻转 180 度。
  2. 多张中间层动画思路
      如果有多张中间层,那么就需要在每张中间层上都做动画。由于需要展现错开翻牌的效果,所以每张中间层的动画需要错开一定的时间。
      另外,由于多张中间层的存在,所以需要考虑到层级的问题。
    • 在动画执行到一半(翻转到 90 度)以前:数字小的层级高于数字大的层级。
    • 在动画执行到一半以后:数字大的层级高于数字小的层级。

实现过程

  1. 数据结构
    属性 类型 说明
    value Number 需要展示的数字(组件入参)
    processValue Array 需要展示的数字的每一位过程数字(组件内部计算值)
    uniqueId String 组件唯一标识(组件内部计算值)
  2. 视图结构
    主要设计思路和层级已经在注释中给出。
<!-- 最外层容器,用于给出uniqId来防止gsap动画冲突 -->
<div class="container-nf" :class="[uniqueId]">
  <!-- 底部的上半部分 -->
  <div class="flip-item flip-item__base flip-item__base--top">
    <span> {{ processValue.slice(-1)[0] }} </span>
  </div>
  <!-- 底部的下半部分 -->
  <div class="flip-item flip-item__base flip-item__base--bottom">
    <span> {{ processValue.slice(0, 1)[0] }} </span>
  </div>
  <!-- 中间的过程部分 -->
  <template v-for="(i, index) in processValue.slice(0, -1)">
    <!-- 中间的过程部分的正面 -->
    <div
      :key="`${index + 1}-front-${i}`"
      :id="`over-${index + 1}-front`"
      class="flip-item flip-item__over flip-item__over--front"
      :style="{ zIndex: 15 - index }"
    >
      <span> {{ i }} </span>
    </div>
    <!-- 中间的过程部分的反面 -->
    <div
      :key="`${index + 1}-back-${i}`"
      :id="`over-${index + 1}-back`"
      class="flip-item flip-item__over flip-item__over--back"
      :style="{ zIndex: 15 - index }"
    >
      <span> {{ processValue[index + 1] }} </span>
    </div>
  </template>
</div>

注意,下面的 css 中,可根据个人习惯来实现,不一定是上面我给出的写法。其中比较重要点有:
transform-origin的设置,这个属性决定了元素翻转的轴心。
backface-visibility的设置,这个属性决定了元素翻转后的背面是否可见。

.container-nf {
  position: relative;

  perspective: 400px;
}

.flip-item {
  font-family: Bebas;
  font-size: 40px;

  // 对文字的溢出做隐藏
  overflow-y: hidden;

  width: 100%;
  // 留出中间的空隙
  height: calc(100% / 2 - 0.5px);

  color: #409eff;
  background-color: #d3d3d3;

  // 上半部分的背景和字体颜色
  &__base--top,
  &__over--front {
    border-radius: 3px 3px 0 0;
    background-color: #fafafa;
    // 控制字体便宜,使其垂直居中
    span {
      position: relative;
      top: 14px;
    }
  }

  // 下半部分的背景和字体颜色
  &__base--bottom,
  &__over--back {
    border-radius: 0 0 3px 3px;
    background-color: #fff;

    span {
      position: relative;
      bottom: 2.4px;
    }
  }

  // 底部
  &__base {
    position: absolute;

    // 底部上半部分
    &--top {
      line-height: 100%;

      top: 0;

      box-shadow: 0 0 2px 0 rgba(102, 102, 102, 0.25);
    }

    // 底部下半部分
    &--bottom {
      // 行高为0就直接在卡片里显示文字的下半不分了
      line-height: 0;

      bottom: 0;

      box-shadow: 0 2px 2px 0 rgba(102, 102, 102, 0.25);
    }
  }

  // 顶部
  &__over {
    position: absolute;
    z-index: 2;

    // 重要!背面不可见
    backface-visibility: hidden;

    //顶部正面
    &--front {
      line-height: 100%;

      top: 0;

      transform: rotateX(0deg);
      // 使其以中间空隙处为轴翻转
      transform-origin: 50% calc(100% + 0.5px);
    }

    &--back {
      line-height: 0;

      bottom: 0;
      // 给出初始翻转角度,让它被藏在正面的背后
      transform: rotateX(180deg);
      // 使其以中间空隙处为轴翻转
      transform-origin: 50% -0.5px;
    }
  }
}
  1. 逻辑部分
  • 工具函数-计算中间值
/**
 * @description 计算中间值
 * @param {Number} start 开始值
 * @param {Number} end 结束值
 * @return {Array} 中间值
 * @example
 * getProcessValues(1, 5); // [1, 2, 3, 4, 5]
 * @example
 * getProcessValues(0, 0); // [0]
 * @example
 * getProcessValues(9, 1); // [9, 0, 1]
 */
function getProcessValues(start, end) {
  const result = [];
  if (start <= end) {
    for (let i = start; i <= end; i++) {
      result.push(i);
    }
  } else {
    for (let i = start; i <= end + 10; i++) {
      result.push(i % 10);
    }
  }
  return result;
}
  • 主要逻辑
watch: {
  value(val, oldVal) {
    this.$nextTick(() => {
      this.processValue = getProcessValues(oldVal, val)
      this.$nextTick(() => {
        // 遍历所有过程值
        this.processValue.slice(0, -1).forEach((value, index) => {
          // 获取当前索引的正面和背面元素
          const front = document.querySelector(`.${this.uniqueId} #over-${index + 1}-front`)
          const back = document.querySelector(`.${this.uniqueId} #over-${index + 1}-back`)
          // 设置初始位置和层级,其中数字越小的层级越大(在顶部)(默认值的变化从小到大)
          gsap.set(front, {
            rotationX: 0,
            zIndex: 15 - index,
            filter: 'drop-shadow(0px 0px 0px rgba(102, 102, 102, 0.25))'
          })
          gsap.set(back, {
            rotationX: 180,
            zIndex: 15 - index,
            filter: 'drop-shadow(0px 0px 0px rgba(102, 102, 102, 0.25))'
          })
          // 正面动画
          gsap.to(front, {
            // 根据索引设置动画延迟,实现逐个翻转的效果
            delay: 0.1 * index,
            keyframes: [
              // 关键帧,分为两段,第一段是从0度旋转到-90度,第二段是从-90度旋转到-180度,由于翻到下面就不需要阴影和透明度,所以这里采用关键帧的方式
              { duration: 0.5, ease: 'power3.in', rotationX: -90, opacity: 0.9, filter: 'drop-shadow(0px 0px 2px rgba(102, 102, 102, 0.25))' },
              { duration: 0.5, ease: 'power3.out', rotationX: -180, opacity: 1 }
            ],
            onUpdate: () => {
              const rotationX = gsap.getProperty(front, 'rotationX')
              // 当旋转角度达到-90度时,将当前元素的层级设置为当前索引+2(越大的数字层级越大)
              if (rotationX <= -90) {
                gsap.set(front, {
                  zIndex: index + 2,
                })
              }
            }
          })
          // 背面动画
          gsap.to(back, {
            delay: 0.1 * index,
            keyframes: [
              { duration: 0.5, ease: 'power3.in', rotationX: 90, opacity: 0.9, filter: 'drop-shadow(0px 0px 0px rgba(102, 102, 102, 0.25))' },
              { duration: 0.5, ease: 'power3.out', rotationX: 0, opacity: 1 }
            ],
            onUpdate: () => {
              const rotationX = gsap.getProperty(back, 'rotationX')
              // 同上(由于dom结构,背面就是默认在正面的后面一层的,不需要单独设置特殊值来控制了)
              if (rotationX >= 90) {
                gsap.set(back, {
                  zIndex: index + 2
                })
              }
            }
          })
        })
      })
    })
  }
}

尾声

  1. 其实网上有很多类似的文章和工具类库,但是我没有找到使用 GreenSock 的方案,所以就自己写了一个,希望能帮到大家。
  2. 字体大小、位置等可能需要根据实际情况做调整。
  3. GreenSock真的很好用,API也很丰富,推荐大家使用。

Vue项目Build后自动打包

1. 安装依赖

npm install filemanager-webpack-plugin

2. vue.config.js 配置

const FileManagerPlugin = require('filemanager-webpack-plugin')
...
// isProd 一般为环境判断 如 process.env.NODE_ENV === 'production'
isProd &&
  plugins.push(
    new FileManagerPlugin({
      events: {
        onEnd: {
          // 首先先删除之前的文件
          delete: ['./dist.zip'],
          // 压缩 源->目的地
          archive: [
            {
              source: path.join(__dirname, './dist'),
              destination: path.join(__dirname, './dist.zip')
            }
          ]
        }
      }
    })
  )
...
const vueConfig = {
  ...
  configureWebpack: {
    ...
    plugins,
    ...
  }
  ...
}

3. filemanager-webpack-plugin 简易教程

Github

1. Options

new FileManagerPlugin({
  events: {
    onStart: {}, //打包前
    onEnd: {}, //打包结束后
  },
  runTasksInSeries: false,
  runOnceInWatchMode: false,
});

2. Actions

  • Copy
    • source[string] - 源(文件/目录/glob)
    • destination[string] - 文件/目录
    • options [‘object`] - copy options
      • flat: [Boolean]
      • preserveTimestamps: [Boolean]
      • overwite: [Boolean]
    • globOptions [object] - options to forward to glob options
  • Delete
  • Move
    • source[string] - a file or a directory or a glob
    • destination[string] - a file or a directory.
  • Mkdir
  • Archive
    • source[string] - a file or a directory or a glob
    • destination[string] - a file.
    • format[string] - Optional. Defaults to extension in destination filename.
    • options[object] - Refer https://www.archiverjs.com/archiver

3. 官方示例

// webpack.config.js:

const FileManagerPlugin = require("filemanager-webpack-plugin");

export default {
  // ...rest of the config
  plugins: [
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [
            { source: "/path/fromfile.txt", destination: "/path/tofile.txt" },
            { source: "/path/**/*.js", destination: "/path" },
          ],
          move: [
            { source: "/path/from", destination: "/path/to" },
            { source: "/path/fromfile.txt", destination: "/path/tofile.txt" },
          ],
          delete: ["/path/to/file.txt", "/path/to/directory/"],
          mkdir: ["/path/to/directory/", "/another/directory/"],
          archive: [
            { source: "/path/from", destination: "/path/to.zip" },
            { source: "/path/**/*.js", destination: "/path/to.zip" },
            { source: "/path/fromfile.txt", destination: "/path/to.zip" },
            {
              source: "/path/fromfile.txt",
              destination: "/path/to.zip",
              format: "tar",
            },
            {
              source: "/path/fromfile.txt",
              destination: "/path/to.tar.gz",
              format: "tar",
              options: {
                gzip: true,
                gzipOptions: {
                  level: 1,
                },
                globOptions: {
                  // https://github.com/Yqnn/node-readdir-glob#options
                  dot: true,
                },
              },
            },
          ],
        },
      },
    }),
  ],
};

Cesium之Vue环境配置与demo运行(一)

背景

最近公司有新项目(据说是关于数字孪生),需要用到Cesium来展示3d模型。由于我技术栈是Vue,故在此记录环境配置、安装相关的一些要点。

Vue项目创建

本次Demo尝试使用Vue3来搭建。

  1. 通过Vue-CLI ^4.5+ 脚手架来创建V3项目
    # 安装vli(按需)
    yarn global add @vue/cli
    # OR
    npm install -g @vue/cli
    # 创建项目
    vue create hello-world
    创建过程中注意选择V3即可,其他配置按自己喜好。
  2. 项目创建完成后,在项目下安装sass相关依赖。(按需)
    npm install node-sass
    npm install sass-loader
    由于node-sass的版本和nodejs版本依赖关系比较魔幻,故在安装的时候需要注意和本地的node版本匹配。下放依赖匹配表。
    NodeJS Supported node-sass version Node Module
    Node 15 5.0+ 88
    Node 14 4.14+ 83
    Node 13 4.13+, <5.0 79
    Node 12 4.12+ 72
    Node 11 4.10+, <5.0 67
    Node 10 4.9+ 64
    Node 8 4.5.3+, <5.0 57
    Node <8 <5.0 <57
  3. 安装cesium
    npm install cesium
  4. 安装webpack相关依赖
    copy-webpack-plugin
    css-loader”
    html-webpack-plugin
    strip-pragma-loader
    style-loader
    uglifyjs-webpack-plugin
    url-loader
    webpack
    webpack-cli
    webpack-dev-server
  5. 在项目文件夹下新建vue.config.js
    const path = require("path");
    
    
    const webpack = require('webpack');
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    const resolve = function(dir) {
      return path.join(__dirname, dir);
    };
    module.exports = {
      publicPath: process.env.NODE_ENV === "production" ? "./" : "./",
      outputDir: "dist",
      assetsDir: "static",
      lintOnSave: true, // 是否开启eslint保存检测
      productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
      chainWebpack: config => {
        config.resolve.alias
          .set("@", resolve("src"))
          .set("@v", resolve("src/views"))
          .set("@c", resolve("src/components"))
          .set("@u", resolve("src/utils"))
          .set("@s", resolve("src/service")); /* 别名配置 */
        config.optimization.runtimeChunk("single");
      },
      devServer: {
        // host: "localhost",
        /* 本地ip地址 */
        //host: "192.168.1.107",
        host: "0.0.0.0", //局域网和本地访问
        port: "8080",
        hot: true,
        /* 自动打开浏览器 */
        open: false,
        overlay: {
          warning: false,
          error: true
        },
        /* 跨域代理 */
      },
      configureWebpack:{
          plugins: [
        // Copy Cesium Assets, Widgets, and Workers to a static directory
        new CopyWebpackPlugin({
            patterns: [
                { from: 'node_modules/cesium/Build/Cesium/Workers', to: 'Workers' },
                { from: 'node_modules/cesium/Build/Cesium/ThirdParty', to: 'ThirdParty' },
                { from: 'node_modules/cesium/Build/Cesium/Assets', to: 'Assets' },
                { from: 'node_modules/cesium/Build/Cesium/Widgets', to: 'Widgets' }
            ],
        }),
        new webpack.DefinePlugin({
            // Define relative base path in cesium for loading assets
            CESIUM_BASE_URL: JSON.stringify('')
        })
    ]
      }
      ,
    };
  6. 在你的HelloWorld里面写cesium相关逻辑

    这里我直接贴上我的HelloWorld
    PS: 其中token自己在Cesium官网里面申请就行了

    <!--
     * @Author: 王欣磊
     * @Date: 2021-05-06 11:17:20
     * @LastEditors: 王欣磊
     * @LastEditTime: 2021-05-06 15:57:10
     * @Description: 
     * @FilePath: /test3/src/components/HelloWorld.vue
    -->
    <template>
      <div class="hello">
        <div id="cesiumContainer"></div>
        <h1 @click="clickChoose">{{ message }} {{item.title}}</h1>
        <p>
          For a guide and recipes on how to configure / customize this project,<br>
          check out the
          <a href="https://cli.vuejs.org" target="_blank" rel="noopener">vue-cli documentation</a>.
        </p>
        <h3>Installed CLI Plugins</h3>
        <ul>
          <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-babel" target="_blank" rel="noopener">babel</a></li>
          <li><a href="https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-eslint" target="_blank" rel="noopener">eslint</a></li>
        </ul>
        <h3>Essential Links</h3>
        <ul>
          <li><a href="https://vuejs.org" target="_blank" rel="noopener">Core Docs</a></li>
          <li><a href="https://forum.vuejs.org" target="_blank" rel="noopener">Forum</a></li>
          <li><a href="https://chat.vuejs.org" target="_blank" rel="noopener">Community Chat</a></li>
          <li><a href="https://twitter.com/vuejs" target="_blank" rel="noopener">Twitter</a></li>
          <li><a href="https://news.vuejs.org" target="_blank" rel="noopener">News</a></li>
        </ul>
        <h3>Ecosystem</h3>
        <ul>
          <li><a href="https://router.vuejs.org" target="_blank" rel="noopener">vue-router</a></li>
          <li><a href="https://vuex.vuejs.org" target="_blank" rel="noopener">vuex</a></li>
          <li><a href="https://github.com/vuejs/vue-devtools#vue-devtools" target="_blank" rel="noopener">vue-devtools</a></li>
          <li><a href="https://vue-loader.vuejs.org" target="_blank" rel="noopener">vue-loader</a></li>
          <li><a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">awesome-vue</a></li>
        </ul>
      </div>
    </template>
    
    <script>
    import * as Cesium from 'cesium';
    import "cesium/Build/Cesium/Widgets/widgets.css";
    import { onMounted, ref,reactive } from 'vue'
    export default {
      name: 'HelloWorld',
      props: {
        msg: String
      },
      setup(){
        const message = ref('choose')
        const item = reactive({title:'name'})
        onMounted(()=>{
            // Your access token can be found at: https://cesium.com/ion/tokens.
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlYWY5NzY4Yy1mY2YyLTRmYTgtYjAyMy1hMGY3MTllZmVmNDUiLCJpZCI6NTQ4ODMsImlhdCI6MTYyMDI3MzA1NX0.M-B79nr0L9j3L3RmNwmGisLrQz5ux7vRKv7TbP4qxkU';
        // Initialize the Cesium Viewer in the HTML element with the `cesiumContainer` ID.
        const viewer = new Cesium.Viewer('cesiumContainer', {
          terrainProvider: Cesium.createWorldTerrain()
        });    
        // Add Cesium OSM Buildings, a global 3D buildings layer.
        // eslint-disable-next-line no-unused-vars
        const buildingTileset = viewer.scene.primitives.add(Cesium.createOsmBuildings());   
        // Fly the camera to San Francisco at the given longitude, latitude, and height.
        viewer.camera.flyTo({
          destination : Cesium.Cartesian3.fromDegrees(-122.4175, 37.655, 400),
          orientation : {
            heading : Cesium.Math.toRadians(0.0),
            pitch : Cesium.Math.toRadians(-15.0),
          }
        });
        })
        return { message,item}
      },
      methods:{
        clickChoose(){
          this.message+='0'
          this.item.title+='p'
        }
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped lang="scss">
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    
  7. 运行devServer就完事了

热区扩大-Vue组件

废话不多说直接上代码

<template>
  <view class="parent">
    <slot></slot>
    <view :class="['expand',area]" @click.stop="emit"></view>
  </view>
</template>

<script>
  export default {
    name: "ExpandClickArea",
    props: {
      area: {
        //small,normal,big,large
        default: "normal",
        type: String,
      },
    },
    methods: {
      emit() {
        this.$emit("expandOnClick");
      },
    },
  };
</script>

<style scoped>
  .parent {
    position: relative;
    overflow-x: visible;
    overflow: visible;
  }
  .expand {
    position: absolute;
  }
  .normal {
    top: -10px;
    right: -10px;
    bottom: -10px;
    left: -10px;
  }
  .small {
    top: -5px;
    right: -5px;
    bottom: -5px;
    left: -5px;
  }
  .big {
    top: -15px;
    right: -15px;
    bottom: -15px;
    left: -15px;
  }
  .large {
    top: -20px;
    right: -20px;
    bottom: -20px;
    left: -20px;
  }
</style>