VueRouter Basic tutorial series 🎉

The first thing to notice about using VueRouter as a CompositionAPI is that the component instance cannot be accessed through this in Setup. This does not affect the template’s binding to the component instance (meaning that the $route and $Router objects can still be accessed through the component instance in the template).

The route with the router

This.$router and this.$route cannot be accessed directly because the component instance cannot be accessed through this in Setup. Instead, we use the useRouter function to get the route and router objects, respectively.

const {route, router} = useRouter();
Copy the code

⚠️ Note that the route object is reactive throughout, so we want to avoid listening for the entire Route object and listen for its specific properties instead.

watch(() = >route.params, async newParams=> {
   userData.value = await fetchUser(newParams.id)
});
Copy the code

Route navigation guard

VueRouter provides navigational guards for the combined onBeforeRouteUpdate and onBeforeRouteLeave functions.

import { defineComponent, onBeforeRouteUpdate, onBeforeRouteLeave } from 'vue';

defineComponent({
    setup() {
        // Rerequest data after path parameters change.
        onBeforeRouteUpdate(async (to, from) = > {if(to.params.id ! = =from.params.id) {
                userData.value = await fetchUser(to.params.id)
            }
        });

        onBeforeRouteLeave((to, from) = > {
            const answer = window.confirm(
                'Do you really want to leave? you have unsaved changes! '
            )
            // Unnavigate and stay on the same page
            if(! answer)return false}}}));Copy the code

⚠️ Keep in mind that VueRouter only provides these two combined function-style navigational guards, not the beforeRouteEnter.

OnBeforeRouteUpdate is triggered when the route component is reused when only the path parameters, query, hash are changed, but not when the path is changed.

useLink

The useLink composite exposes the behavior and information generated within a router-link component as it navigates. These behaviors and information are identical to the attributes received through the Router-link scope slot (V-slot).

<router-link v-slot="{route, href, isActive, isExactActive, navigat}">
    {{href}}
</router-link>
Copy the code

The parameters received by the useLink function are exactly the same as those received by router-link.

This means that you can use the useLink function to obtain the behavior and information generated by a router-link jump, but the jump does not actually occur.

const { route, href, isActive, isExactActive, navigate } = useLink({to:'/'}); 
Copy the code

We can think of useLink’s functionality as a pre-parsing of router-link. Through pre-parsing, we can repackage router-link to deal with different types of link jumps in a richer way, such as internal links, external links (third-party links), whether a new window opens, etc.

import { RouterLink, useLink } from 'vue-router'

export default {
  name: 'AppLink'.props: {
    // If using TypeScript, add @ts-ignore. RouterLink.props,inactiveClass: String,},setup(props) {
    const { route, href, isActive, isExactActive, navigate } = useLink(props)

    const isExternalLink = computed(
      () = > typeof props.to === 'string' && props.to.startsWith('http'))return { isExternalLink, href, navigate, isActive }
  },
}
Copy the code

⚠️ For the performance and security of our page, it is strongly recommended to set rel=”noopener” for a tag when reconnecting to third-party links.