Search code examples
vue.jsvuejs3vue-routervue-composition-api

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


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:

  1. How can I access the value from the top setup segment into my regular <setup>?
  2. Is this even an accepted Vue pattern? If not, is there any other way to get more information about the from-path than just the path itself (e.g. names of previous components) using the Composition API?

Solution

  • 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>