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

如何在Nuxt项目中全局获取nuxt.config.js中的配置值?

在Nuxt项目中全局获取nuxt.config.js配置值的方法

根据Nuxt版本不同,获取配置的方式略有区别,以下是对应实现方案:

Nuxt 2 场景

组件模板中直接访问

在模板里通过$config全局变量直接调用配置项:

<template>
  <div>{{ $config.myObject.myString }}</div>
</template>

组件脚本中访问

在脚本里通过this.$config获取配置:

<script>
export default {
  mounted() {
    console.log(this.$config.myObject.myString) // 输出 'hello!'
  }
}
</script>

Nuxt 3 场景

Nuxt 3使用useRuntimeConfig()来管理配置,需要区分公开配置(客户端可访问)和私有配置(仅服务端可访问):

第一步:配置nuxt.config.ts

将需要在客户端访问的配置放在public字段下:

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      myObject: {
        myString: 'hello!'
      }
    }
  }
})

组件模板中访问

先在脚本中获取运行时配置,再在模板中使用:

<template>
  <div>{{ runtimeConfig.public.myObject.myString }}</div>
</template>

<script setup>
const runtimeConfig = useRuntimeConfig()
</script>

组件脚本中访问

直接调用useRuntimeConfig()获取配置:

<script setup>
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.public.myObject.myString) // 输出 'hello!'
</script>

注:如果是仅服务端可用的私有配置,直接放在runtimeConfig根节点下即可,无需加入public字段,这类配置不会暴露给客户端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:05:39