I am working with a Vue project (Composition API, Single-File Components) where I want to access data about the Vue page I came from. I would really want to access all the data included in the beforeRouteEnter
(about) in the Options API, such as previous component names. However, the Navigation Guards in the Composition API don't have any equivalent to the beforeRouteEnter
guard.
I have tried to add a separate <setup>
segment above the main <setup script>
segment, but I don't know how to access the values I have in the separate setup from my original setup:
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
beforeRouteEnter(to, from) {
...
},
});
</script>
<script lang="ts" setup>
// How to access to/from in here?
</script>
My questions are then:
<setup>
?beforeRouteEnter
is not available in setup()
. But it's a special hook, which is run before setup()
(unlike most other hooks), so you could pass data from it to setup()
using an external store:
routerStore.ts
import { reactive } from 'vue'
export const state = reactive({
from: null,
to: null
})
View:
<script lang="ts">
import { state } from './routeStore'
export default defineComponent({
beforeRouteEnter(from, to) {
Object.assign(state, { from, to })
}
})
</script>
<script lang="ts" setup>
import { state } from './routeStore'
console.log(state)
</script>