javascriptvue.jsvue-componentvue-routervue-sfc

How to detect if vue-router is used in current Vue instance?


I want to develop a library with vue.js component inside. This component will have navigation elements inside. I want it to work with and without vue router. In router mode it should use <router-link> and if no router is used it should return standard <a> tags.

<template>
       <div>
            <div v-if="vueRouterIsUsed">
                <router-link v-bind:to="url">Router link</router-link>
            </div>
            <div v-else>
                <a :href="url">No router</a>
            <div>
       </div>
</template>
<script>
    export default{
        props: {
            url: {
                type: String,
            }
        }
    }
</script>
  1. How to detect if vue-router is used in current Vue instance?
  2. Is there a better way that if/else for doing <router-link> to <a> fallback if no router is installed?

Solution

  • You can check in the created (or mounted) lifecycle hook what is in this.$router you can access all the routes and the router object, which means you can check what you need. Set the isRouter variable based on that.