在Nuxt计算属性中使用$nuxt.$route时遭遇$nuxt is not defined错误的技术求助
Hey there! Let's break down what's going on here and get your code back on track quickly.
What Caused the Sudden Error?
In your component's computed property, you're using $nuxt.$route to access the route params—but inside Vue component options like computed or methods, you shouldn't rely on the global $nuxt object directly. The $route object is already attached to the Vue component instance, so you need to reference it via this.$route instead.
The sudden failure might stem from a few scenarios:
- A Nuxt version update that adjusted how the global
$nuxtobject is injected during server-side rendering (SSR) - A context mismatch where
$nuxtwasn't fully initialized when the computed property ran (common in SSR environments) - A subtle configuration change that disabled the global injection of
$nuxt
The Fixed Code
Here's the adjusted version of your code that will work reliably:
computed: { updateActiveRoute() { // Use this.$route instead of $nuxt.$route, and simplify the fallback logic return this.$route.params.name || 'Hello' } }, watch: { updateActiveRoute(newVal) { this.activeRoute = newVal } }
Why This Works
this.$routeis the standard, consistent way to access the current route in Vue/Nuxt components—it works seamlessly on both server and client sides.- The global
$nuxtobject is intended for use in templates or non-component contexts (like plugins), not inside component options wherethisgives you direct access to the instance. - Using
||instead of the ternary operator cleans up the code while maintaining the same fallback behavior (using 'Hello' whennameis falsy).
Bonus: Streamline Your Code Even More
Since you're watching the computed property to update activeRoute, you can eliminate the watcher entirely by making activeRoute a computed property directly:
computed: { activeRoute() { return this.$route.params.name || 'Hello' } }
This cuts down on redundant code and keeps your reactivity logic simpler.
内容的提问来源于stack exchange,提问作者JMKelley

