user379888
user379888

Reputation:

How to make a dynamic Vue navbar?

I have below navbar in Vue. When I pass an array to it it doesn't show the menu.

<template>
  <div>
    <div class="mt-5 px-2">

    <li v-for="item in items" :key="item.name">

      <a
        href="item.link"
        class="group flex items-center px-2 py-2 text-base leading-6 font-medium rounded-md text-white bg-gray-900 focus:outline-none focus:bg-gray-700 transition ease-in-out duration-150"
      >
        <svg
          class="mr-4 h-6 w-6 text-gray-300 group-hover:text-gray-300 group-focus:text-gray-300 transition ease-in-out duration-150"
          stroke="currentColor"
          fill="none"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M3 12l9-9 9 9M5 10v10a1 1 0 001 1h3a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1h3a1 1 0 001-1V10M9 21h6"
          />
        </svg>

      {{ item.name }}

       </a>
    </li>
    </div>
  </div>
  <!--
 items: [
      { name: 'Foo' },
      { link: 'Bar' }
    ]
  -->
</template>

<script>
export default {
  name: 'Nav',
  props: ['items'],
  data() {
    return {
      parents: [],
    };
  },
};
</script>

<style scoped></style>

Upvotes: 2

Views: 702

Answers (2)

Fima Taf
Fima Taf

Reputation: 977

The main problem in your example is that you named your component Nav, but HTML5 already has this element which will cause a collision between your component and HTML's element, just rename into something else.

After you change the name make sure that the array that you pass to that component looks like this - [{name: 'a', link: 'http://a.com'}, {name: 'b', link: 'http://b.com'}].

Upvotes: 1

cello
cello

Reputation: 5486

Your items-array you show as example data is unsuitable for the template:

the items-array contains two objects, one with a single property name, the other with a single property link. But based on the template it looks as if name and link should be part of the same object, e.g.:

items: [
    { name: 'Foo1', 'link': 'Bar1' },
    { name: 'Foo2', 'link': 'Bar2' }
]

With the original array passed as by your example, there will likely be an error shown in the browser's console due to item.link not being defined for the first object, and thus probably stopping the rendering process of Vue.

Upvotes: 2

Related Questions