[Vuejs]-In Vue3, how can I access properties similar to those in "beforeRouteEnter" in the Composition API?

1👍

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>
👤tao

0👍

This cannot be done with script setup, it is sugar syntax for the body of setup function, which is called on route component instantiation, while beforeRouteEnter hook is supposed to be triggered before component instantiation.

script setup covers only the most common cases, any any other it should be coupled or replaced with script:

<script>
export default {
  beforeRouteEnter() { ... }
}
</script>

<script setup>...</script>

As long as beforeRouteEnter is used for asynchronous route initialization, it can be replaced with asynchronous setup, which is supported by Vue router:

<script setup>
await ...
...
</script>

Leave a comment