[Vuejs]-How to implement the Three.js scene example in Vue 3?

1👍

Here is an answer for fellow seekers. Luckily there are places in the internet where the people are less snobbish about perfectly valid questions [1].

App.vue

<script setup>
import { ref, onMounted } from 'vue';
import * as THREE from 'three';

const target = ref();

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(500, 500);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
  requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render(scene, camera);
}

onMounted(() => {
  target.value.appendChild(renderer.domElement);
  animate();
});
</script>

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

[1] https://github.com/vuejs/core/discussions/9057

Leave a comment