There is already a popular npm for vue + babylonjs integration vue-babylonjs
, so my intention is not to build a replacement integration (even though that library has no updates in > 2 years), but I did want to learn how a vue integration works, so I used (ie: shameless copied many parts of) the existing troij.js (three + vue) as a starting point and ported to babylon a proof of concept.
I have been working in Vue 3 at work for about 18 months and love some things about Vue over other libraries like React. Instead of using Vuex or any state management library I write my own stores using computed
and refs
, which can be built much like React hooks, but have a better data binding and developer experience IMO. I have written custom Vue components that emit events and there are some other excellent parts of Vue that I find it hard to work without. I also really like how troij.js with vite works seamlessly with HMR. In my sample screen capture below I am editing the :beta
and :radius
camera properties in my vue template and it was reflected in the scene, so I could see how the developer experience would be what I was after as well.
I only spent about 2.5 hours on it and have only 1 camera and 1 geometry working.
End user code looks like this:
<template>
<Engine ref="engine" antialias resize="window">
<Scene>
<ArcRotateCamera :beta="Math.PI / 8" />
<HemisphericLight />
<Box :size="1" ref="box"/>
</Scene>
</Engine>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { Box, Engine, MeshPublicInterface, EnginePublicInterface, Scene } from './export'
export default defineComponent({
components: { Box, Engine, Scene },
mounted() {
const engineSetup = this.$refs.engine as EnginePublicInterface
const mesh = (this.$refs.box as MeshPublicInterface).mesh
if (engineSetup && mesh) {
engineSetup.engine.onBeginFrameObservable.add(() => {
mesh.rotation.x += 0.01
})
}
},
})
</script>
You can see HMR in progress here:
So, not much to it to build a reusable library. Including creating this post I am at something like 2.5 hours total time. There is obviously a looooong way to go with increasing Babylon API support either dynamically or manually/code generation. Not sure if the experiment will end here as I have so many other projects on the go, but wanted to share this.
Also, if you only need a few parts of babylonjs then you could fork this and add just what you need to the plugins and it should tree-shake down really well to a small static site. If you run yarn dev
it will run the website above with a spinning cube.
oh. and the link: brianzinn/vite-babylonjs: learning experiment porting trois.js (github.com)