本文已参与新文创作礼活动,一起开启掘金创作之路
VUE 加载 three.js 资源
踩坑1(静态变量写在vue的data内)
误点1:在上手vue的过程中感受到监控data的变化特别神奇,误以为应该把所有的变量都定义在vue的data内,直接this.scene等方式加载就好了。
<template>
</template>
<script>
import * as THREE from 'three/';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
...
export default {
data(){
return{
scene: null,
camera: null,
renderer: null,
controls: null
...
}
},
methods:{
init();
}
}
</script>
<style >
</style>
踩坑2(抽离完整的threejs代码到单独的js文件内,在vue文件对js文件加载)
误点2:在使用vue的过程中理解到vue的data内的数据应该是受监控的内容会经常产生变更的数据,需要根据值的变化去刷新dom的内容,而不应该是长期不会变化的静态数据资源,所以将threejs内容重新进行抽离到js文件内加载。
//three.js
import * as THREE from 'three/';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
...
function init(){
var scene, camera, renderer, controls,...;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera();
...
}
export init;
<template>
</template>
<script>
import init from 'three.js';
...
export default {
data(){
return{
}
},
methods:{
init();
}
}
</script>
<style >
</style>
最终理解
结论:抽离后的js使用不方便与vue组件的传值,使得three的使用与vue的特性断连,原本设想的vue+three的技术结构变回了纯js技术去实现,没有使用到vue提供的便利,因此应当还是将js内容写回到vue文件进行使用。在上次偶然发现别人直接将 静态变量的声明写在最上方后才恍然大悟,自己给自己绕了一大圈,因此静态变量应当是申明在最上层就好了(害羞.png,尴了个大尬~)。
<template>
</template>
<script>
import * as THREE from 'three/';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';
...
var scene, camera, renderer, controls,...;
export default {
data(){
return{
}
},
methods:{
init(){
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera();
...
}
}
}
</script>
<style >
</style>