As the error message suggests, accessing the 'container.value' property of the 'container' ref may result in 'null'. To fix this, you can use the optional chaining operator ?. to access the 'value' property only if 'container' is not 'null':

<template>
  <div ref="container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as THREE from 'three'

const container = ref(null)
let scene: any = null
let camera: any = null
let renderer: any = null

const setScene = () => {
  scene = new THREE.Scene()
  scene.background = new THREE.Color(0x001219)
}

const setCamera = () => {
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    5000
  )
  camera.position.set(0, 0, 8)
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  scene.add(camera)
}

const setRenderer = () => {
  renderer = new THREE.WebGLRenderer({
    antialias: true
  })
  renderer.setSize(window.innerWidth, window.innerHeight)
  container.value?.appendChild(renderer.domElement) // optional chaining operator
}

const init = () => {
  setScene()
  setCamera()
}

onMounted(() => {
  setRenderer()
  init()
})
</script>
Vue3 + Three.js: 解决 'container.value' 为 null 的错误

原文地址: https://www.cveoy.top/t/topic/mQdc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录