Skip to content

Vue Router – Router Composition API & Lazy Loading

Table of Contents

    Composition API

    export default {
      setup() {
        const router = useRouter()
        const route = useRoute()
    
        router.push()
    
      },
    }

    Tracking Route Changes

    The route object is a reactive object, so any of its properties can be watched and you should avoid watching the whole route object

    setup() {
        const route = useRoute()
        const userData = ref()
    
        watch(
          () => route.params,
          async newParams => {
            userData.value = await fetchUser(newParams.id)
          }
        )
    }

    Guards

    onBeforeRouteLeave & onBeforeRouteUpdate

    import { onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router'
    
    export default {
      setup() {
        onBeforeRouteLeave((to, from) => { })
    
        const userData = ref()
    
        onBeforeRouteUpdate(async (to, from) => {
          if (to.params.id !== from.params.id) {
            userData.value = await fetchUser(to.params.id)
          }
        })
      },
    }

    useLink

    <template>
      <a v-if="isExternalLink" v-bind="$attrs" :href="to" target="_blank">
        <slot />
      </a>
      <router-link v-else v-bind="$props" custom v-slot="{ isActive, href, navigate }">
        <a
          v-bind="$attrs"
          :href="href"
          @click="navigate"
          :class="isActive ? activeClass : inactiveClass"
        >
          <slot />
        </a>
      </router-link>
    </template>
    
    <script>
    import { RouterLink } from 'vue-router'
    
    export default {
      name: 'AppLink',
    
      props: {
        // add @ts-ignore if using TypeScript
        ...RouterLink.props,
        inactiveClass: String,
      },
    
      computed: {
        isExternalLink() {
          return typeof this.to === 'string' && this.to.startsWith('http')
        },
      },
    }
    </script>

    Usage

    <template>
      <AppLink
        v-bind="$attrs"
        class="inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-gray-500 focus:outline-none transition duration-150 ease-in-out hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700 focus:border-gray-300 transition duration-150 ease-in-out"
        active-class="border-indigo-500 text-gray-900 focus:border-indigo-700"
        inactive-class="text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:text-gray-700 focus:border-gray-300"
      >
        <slot />
      </AppLink>
    </template>
    Published inVue Router

    Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *