动态更改"to"属性 在路由器链路 vue 中



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

我使用路由器链接生成了侧边栏列表

<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"(时,它是有效的,但我希望这些路径是根据我单击的列表元素动态生成的。

以下是我的操作方法。尝试在上面的级别上提取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'}"

这个带有switch和程序化路由器更改的解决方案怎么样

<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>

也许我的答案对某人有用,所以我发布了我的解决方案。我并没有找到从一个数据文件中分别循环导航条元素和从路由文件中循环路由器lik:to路径属性的解决方案。

如果我对所有内容都使用路由文件,它就会起作用。

<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>

最新更新