Search code examples
javascriptvue.jsrouterlinkv-for

cannot bind path dynamically on vuejs with router-link and v-for


I'm having trouble rendering router-link properly with v-for directive.

What I want is that, I want the side menu to have a link that leads the user to the page that url corresponds with the name of the side menu element.
So, if the element is 'HOME', it should lead to
myproject.com/HOME.
However, somehow it becomes
myproject.com/Campaign/Campaign/Campaign/HOME
when it is rendered.

I literally have no idea what is going on and I'm seeking for help.

<div id="side">
  <v-navigation-drawer
    fixed
    clipped
    app
    v-model="drawer"
  >
        <v-list dense>
          <template v-for="x in item">
            <div id="no-child" v-if="!x.children">
              <router-link :to="{ path: x.title }">
                <v-list-tile>
                  <v-list-tile-content>
                    <v-list-tile-title>{{x.title}}</v-list-tile-title>
                  </v-list-tile-content>
                </v-list-tile>
              </router-link>
              <v-divider></v-divider>
            </div>
            <div id="with-child" v-else-if="x.children">
              <v-list-gruop>
                  <v-list-tile>
                    <v-list-tile-content>
                      <v-list-tile-title>{{x.title}}</v-list-tile-title>
                    </v-list-tile-content>
                  </v-list-tile>
                  <v-list-tile>
                    <v-list-tile-content v-for="z in x.children">
                      <router-link :to="{ path: x.title}">
                        <v-list-tile-title>{{ z.text }}</v-list-tile-title>
                      </router-link>
                    </v-list-tile-content>
                  </v-list-tile>
                </v-list-gruop>
              <v-divider></v-divider>
            </div>
          </template>
        </v-list>
  </v-navigation-drawer>

export default {
data: () => ({
  drawer: null,
  item: [
    {title: 'HOME'},
    {title: 'Campaign',
      children: [
        {text: 'Start'},
        {text: 'Campaigns'},
        {text: 'Previous'}
      ]
    },
    {title: 'Payment',
      children: [
        {text: 'Pending'},
        {text: 'Completed'}
      ]
    },
    {title: 'Profile'},
    {title: 'Logout'}
  ]
})}

The result of the above is:


Solution

  • <router-link :to="{ path: '/' + x.title }">
    

    the slash is to make sure that you go to the /HOME page under the root directory of your website.