Search code examples
apivue.jsmenunuxt.jshref

Nuxt Menu links from API...How can i detect if its a Nuxt link :to or :href?


Im building my main menu from an API :

  <b-navbar-nav>
        <div v-for="result in resultsmenu" :key="result.id">
       <span class="hoverlink">
  <nuxt-link  :to="result.slug">{{result.title}}</nuxt-link>
    </span>
     </div>
      </b-navbar-nav>

Everythings works well but one problem is in the menu from the API ..One link is external with an "href" like : https://ww.instagram.com so nuxt-link process it like a internal route i end up with :

http://localhost:3000/https://ww.instagram.com

I was wondering if there is a way to tell Nuxt that if a link is an "href" type: "link" to handle it like an external link instead of an nuxt-link to: ?

Thank you


Solution

  • One way to achieve this would be to use a computed property.

    Assuming your resultsmenu data looks something like...

    resultsmenu: [
      {slug: 'http://www.website.com', title: 'link to website.com'},
      {slug: '/test', title: 'link to a website.com'},
      {slug: '/yay', title: 'link to b website.com'},
      {slug: 'http://www.website.com', title: 'link to c website.com'}
    ]
    

    You can do...

    computed: {
      menuLinks() {
        let links = []
        this.resultsmenu.forEach(link => {
          let menuItem = {}
          menuItem.isHttp = !!link.slug.includes('http');
          menuItem.target = link.slug
          menuItem.title = link.title
          links.push(menuItem)
        })
        return links
      }
    }
    

    Then in your template:

    <div v-for="(result, index) in menuLinks" :key="index">
      <span>
        <nuxt-link v-if="!result.isHttp" :to="result.target">{{result.title}}</nuxt-link>
        <a v-else :href="result.target">{{result.title}}</a>
      </span>
    </div>