0

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?
4

2 回答 2

1

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.

于 2019-10-17T14:03:04.667 回答
1

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

于 2022-02-01T20:06:33.960 回答