Nuxt 3 i18n报错:TypeError: _ctx.localPath is not a function 求助
问题解决:Nuxt 3 + Nuxt i18n 中 localePath 调用报错
错误原因
你在<script setup>中声明的localePath是组合式API的局部变量,不会挂载到组件实例的this对象上;同时错误提示里的localPath是拼写错误(少了字母e),这两个原因导致Options API的methods中无法正确调用该方法。
解决方案
方案一:改用组合式API写法(推荐,适配Nuxt 3生态)
直接在<script setup>中定义函数替代Options API的methods,逻辑更统一:
<script setup> import { useLocalePath, useI18n } from '#i18n' import { useRouter } from 'vue-router' const { locale } = useI18n() const localePath = useLocalePath() const router = useRouter() // 定义函数替代methods const exampleMethod = () => { router.push(localePath('/studio')) } </script> <!-- 模板中直接调用 --> <button @click="exampleMethod">跳转到Studio页面</button>
方案二:保留Options API写法
如果需要继续使用Options API,需在普通<script>的setup钩子中获取localePath并暴露给组件实例:
<script> import { useLocalePath, useI18n } from '#i18n' export default { setup() { const { locale } = useI18n() const localePath = useLocalePath() // 将localePath暴露给Options API的this return { localePath } }, methods: { exampleMethod() { // 注意拼写正确:localePath(带e) this.$router.push(this.localePath('/studio')) } } } </script>
内容的提问来源于stack exchange,提问作者Navet56
相关产品推荐
相关产品推荐

