$route throws an undefined error from inside script setup

44 Views Asked by At

I was wondering why this works:

<template> 
<h1> You are on page {{ $route.params.page }}</h1>
</template>

but when I try to access the param from script setup as in

<script setup>
const pageNumber = $route.params.page;
</script>

EsLint throws an error for $route not being defined.

I'm trying to wrap my head around how variables get accessed from within the template compared to from withing script setup.

I'm well aware of the solution to pass said param as a prop and accessing it with defineProps from the component. My question is related to the inner working of Vue. Namely, why variables can be accessed from the template but not from the script.

1

There are 1 best solutions below

3
Piroozeh On

If you want to use these properties in the script setup, you need to import them from their respective modules. For example, if you want to use $route, you need to import useRoute from vue-router and call it in the script setup:

<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
const pageNumber = route.params.page
</script>