You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Nuxt中使用TresJS导入GLTF模型遇问题求助

解决TresJS useGLTF无法加载GLTF模型的问题

问题原因

在Nuxt的服务端渲染(SSR)环境下,直接用/figur.gltf这种根路径调用useGLTF时,服务端无法正确解析该URL(缺少协议、主机等必要信息),从而抛出Failed to parse URL错误。而GLTFModel组件内部已经做了资源路径的适配处理,因此能正常工作。

解决方案

方案1:用Nuxt的useAsset获取正确资源URL

Nuxt提供的useAsset函数会自动处理静态资源路径,确保在SSR/SSG环境下生成合法的URL:

<script setup>
import { OrbitControls, useGLTF, GLTFModel } from '@tresjs/cientos'
import { useAsset } from '#imports'

// 通过useAsset获取适配后的模型路径
const modelPath = useAsset('/figur.gltf')
const { scene, nodes, animations, materials } = await useGLTF(modelPath, { draco: true })
</script>

<template>
  <TresCanvas window-size clear-color="#444444" shadows alpha>
    <TresPerspectiveCamera :position="[500, 500, 500]" :args="[45, 1, 0.1, 100000]"/>
    <OrbitControls />
    <TresAmbientLight :intensity="2" />
    <TresMesh>
      <TresTorusGeometry :args="[1, 0.5, 16, 32]" />
      <TresMeshBasicMaterial color="orange" />
    </TresMesh>
    <Suspense>
       <!-- 注意去掉nodes变量的空格,避免引用错误 -->
       <primitive :object="nodes" />
    </Suspense>
  </TresCanvas>
</template>

方案2:将组件标记为客户端仅执行

如果你的组件不需要服务端渲染,可以直接标记为客户端组件,跳过服务端的路径解析流程:

<!-- 添加client:only属性,强制组件仅在客户端执行 -->
<script setup client:only>
import { OrbitControls, useGLTF, GLTFModel } from '@tresjs/cientos'

const { scene, nodes, animations, materials } = await useGLTF('/figur.gltf', { draco: true })
</script>

<template>
  <TresCanvas window-size clear-color="#444444" shadows alpha>
    <TresPerspectiveCamera :position="[500, 500, 500]" :args="[45, 1, 0.1, 100000]"/>
    <OrbitControls />
    <TresAmbientLight :intensity="2" />
    <TresMesh>
      <TresTorusGeometry :args="[1, 0.5, 16, 32]" />
      <TresMeshBasicMaterial color="orange" />
    </TresMesh>
    <Suspense>
       <primitive :object="nodes" />
    </Suspense>
  </TresCanvas>
</template>

额外注意事项

  • 确保figur.gltf及配套的.bin、纹理文件等放在Nuxt项目的public文件夹根目录下,否则无法通过根路径访问。
  • 代码中:object=" nodes "的空格会导致变量引用失败,必须改为:object="nodes"。

内容的提问来源于stack exchange,提问作者Detlev Spinell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:51:33