当:to属性获取false值时,如何从路由器链接中删除活动类



我在vue中使用router-link作为菜单。我想在routeNamespecificName1specificName2时启用链接。我在:to属性中使用了if子句,并使链接变为diabled和enabeld。但是,当:to属性为false时,它被禁用,但具有活动类。我如何使它被禁用,但有禁用类?

Vue.component('customIcon', {
template: `<svg xmlns="http://www.w3.org/2000/svg" width="15.352" height="15.355" viewBox="0 0 15.352 15.355">
<path id="Union_19" data-name="Union 19" d="M-19.5-15958.5l-7.5,7.5,7.5-7.5-7.5-7.5,7.5,7.5,7.5-7.5-7.5,7.5,7.5,7.5Z" transform="translate(27.176 15966.178)" fill="none" stroke="#bbb" stroke-width="0.5"/>
</svg>`
})
new Vue({
el: "#app",
data() {
return {
routeName: 'specificName1',
menu: [
{to: 'link1', name: 'name1'},
{to: 'link2', name: 'name2'},
{to: 'link3', name: 'name3'}
]
}
}
});
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.css" />
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>

<div id="app">
<div>
<ul>
<router-link
v-for="{ to, name } in menu"
v-slot="{ href, navigate, isActive, isExactActive }"
:key="name"
:to="(routeName === 'specificName1' || routeName === 'specificName2') && to"
>
<li :class="['nav-item', isActive && 'active', isExactActive && 'exact-active']">
<a
v-t="name"
:href="href"
@click="navigate"
/>
</li>
</router-link>
</ul>  
</div>
</div>

当您在路由器链接到属性的同一URL中时,元素类将处于活动状态。

例如,如果您在搜索页面中,以下元素类将活动

<router-link to="/search"></router-link>

我想出了一个解决方案。基于此问题,vue-router不提供disabled属性,因此可以使用CSS来完成此操作。

我试图模拟你的情况,因为我看不到你的片段的结果。如果需要任何更新,请告诉我。

Vue.use(VueRouter)
const Name1 = {
template: `<h1>Name1</h1>`,
}
const Name2 = {
template: `<h1>Name2</h1>`,
}
const Name3 = {
template: `<h1>Name3</h1>`,
}
const specificName1 = {
template: `<h1>specificName1</h1>`,
}
const routes = [{
path: '/name1',
name: 'name1',
component: Name1
},
{
path: '/name2',
name: 'name2',
component: Name2
},
{
path: '/name3',
name: 'name3',
component: Name3
},
{
path: '/specific',
name: 'specificName1',
component: specificName1
},
]
const router = new VueRouter({
routes,
})
var app = new Vue({
el: '#app',
router,
data() {
return {
routeName: 'specificName1',
menu: [{
to: 'link1',
name: 'name1'
},
{
to: 'link2',
name: 'name2'
},
{
to: 'link3',
name: 'name3'
},
{
to: 'specific',
name: 'specificName1'
}
]
}
},
})
a {
color: black;
text-decoration: none;
padding: 1rem;
}
a.router-link-active {
font-weight: bold;
color: green;
text-decoration: underline;
}
.disabled {
pointer-events: none;
}
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>
<!-- App -->
<div id="app">
<nav>
<router-link v-for="{ to, name } in menu" :key="name" :class="{disabled: (name === 'specificName1' || name === 'specificName2')}" :to="{name: name}">{{name}}</router-link>
</nav>
<router-view></router-view>
</div>

最新更新