首页 > 解决方案 > 在router-link vue中动态改变“to”属性

问题描述

我是 Vue 的新手,并且在生成侧边栏列表时犹豫不决,单击时每个列表元素都会打开其组件。我正在使用vue路由器。我理解它应该如何工作的理论,但显然我错过了一些东西,因为我无法解决它。我不知道如何动态更改路径。

我使用 router-link 生成了侧边栏列表

<template>
<div class="sidebarListItems">
    <router-link href="#" 
       :to="calcRut"
       class="list-group-item list-group-item-action bg-light"
       v-for="title in mapTitles" 
       :key="title.map" 
       :title="title.map"
       @click="callMap">
       {{title.map}} 
    </router-link>
</div>
 
</template>

<script>
import bus from "./js/bus"
import mapNames from "./json/popis_karata.json"

export default {
   
   name: "PageSidebarList",
   props: ["title"],

   data(){
       return {
           mapTitles:mapNames,
           ruth=""
       }
   },

   methods: {
        callMap(event){
          bus.$emit("openMap")
        },
        calcRuth(){
          for (var i=0; i<this.routes.length; i++){
          var newruth = this.routes[i].path 
          this.ruth = newruth
        }
    }
    },

    computed: {
      routes(){
      return this.$router.options.routes
      }
   }

当我将路径直接作为字符串 (:to="/zup" 或 :to="/reg") 时,它正在工作,但我希望这些路径是根据我单击的列表元素动态生成的。

标签: javascriptvue.jsvue-router

解决方案


这是我的做法。尝试在上面的级别提取 v-for。如果您不想使用实际元素,请尝试<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>

to=""编辑,也将您的正确格式设置为:to="{name: 'namehere'}"


推荐阅读