[Vuejs]-Dynamically changing "to" attribute In router-link vue

0👍

Maybe my answer would be useful to someone so I am posting my solution.
I didn’t found solution to loop separately navbar elements from one data file and router-lik :to path attribute from routes file.

It work if I use routes file for everything.

<router-link
   v-for="route in $router.options.routes" 
   :key="route.path" 
   :to="route.path"
   class="list-group-item list-group-item-action bg-light">
   {{route.title}} 
</router-link>

2👍

Here’s how I do it. Try extracting the v-for on the level above. If you don’t want to use an actual element, try <template>

<ul class="flex flex-col w-full space-y-1">
  <li v-for="item in items" :key="item.link">
    <router-link class="flex items-center h-8 px-4 rounded-lg hover:bg-white" :class="{ 'bg-white': routeMatches(item) }" :to="{ name: item.link }">
      <div class="text-sm text-gray-700">{{ item.name }}</div>
    </router-link>
  </li>
</ul>

Edit, also format your to="" correctly to be :to="{name: 'namehere'}"

0👍

how about this solution with a switch and a programmatic router change

<template>
  <div id="app">
    <ul class="nav">
      <li class="nav-item" @click="routeChanger('home')">Home</li>
      <li class="nav-item" @click="routeChanger('page1')">Page1</li>
      <li class="nav-item" @click="routeChanger('page2')">Page2</li>
      <li class="nav-item" @click="routeChanger('page3')">Page3</li>
      <li class="nav-item" @click="routeChanger('page4')">Page4</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    routeChanger(routeParam) {
      switch (routeParam) {
        case "home":
          this.$router.push("/home");
          break;
        case "page1":
          this.$router.push("/page1");
          break;

        //...
        default:
          this.$router.push("/404");
          break;
      }
    }
  }
};
</script>

<style>
</style>

Leave a comment