简体   繁体   中英

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?

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.

If you are using Vue3, you can use getCurrentInstance like this:

const isVueRouterInstalled =
  !!getCurrentInstance().appContext.config.globalProperties.$router;

However, as the documentation says:

getCurrentInstance is only exposed for advanced use cases, typically in libraries. Usage of getCurrentInstance is strongly discouraged in application code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM