[英]Removing more than one object from array by string
我正在嘗試實現一個側邊欄,它從 Vue Router 本機$router
對象生成其內容。
因此,它遍歷 routes 數組中存在的所有路由。 但是,我想排除我不想在菜單中顯示的那些。
我嘗試了不同的方法,但沒有按預期工作。 請看下面我現在所擁有的:
<template>
<div class="three cols card card-content">
<aside class="sidebar">
<h6 class="sidebar-label">Navigate</h6>
<ul class="sidebar-list">
<li><router-link to="/"><i class="ico ri-home-4-line"></i>Home</router-link></li>
<li><router-link to="/"><i class="ico ri-swap-box-line"></i>Changelog <i class="medal bg-salmon text-white"> v.1.0 Beta</i></router-link></li>
<li><router-link to="/"><i class="ico ri-question-line"></i>Getting Started</router-link></li>
</ul>
<h6 class="sidebar-label">Documentation</h6>
<ul class="sidebar-list">
<li v-for="route in routes" :key="route"><router-link :to="route.path">{{route.name}}</router-link></li>
</ul>
</aside>
</div>
</template>
<script>
export default {
created() {
//this iterates trough all the routes in order to implement the sidebar menu
const router = this.$router.getRoutes()
router.forEach(route => this.routes.push({
name: route.name,
path: route.path
}));
//this will remove any specific unwanted routes from the menu
this.routes = this.routes.splice((route) => route.name ==! "Home" && route.name ==! "Table of Contents")
},
data(){
return{
routes: []
}
},
}
</script>
任何幫助將不勝感激,
問候,T。
您可以使用 map/filter 方法並替換==!
通過!==
:
created() {
//this iterates trough all the routes in order to implement the sidebar menu
const router = this.$router.getRoutes()
this.routes = router.map(route => ({
name: route.name,
path: route.path
}));
//this will remove any specific unwanted routes from the menu
this.routes = this.routes.filter((route) => route.name !== "Home" && route.name !== "Table of Contents")
},
data(){
return{
routes: []
}
},
更好的解決方案是將路由定義為計算屬性:
computed:{
routes(){
return this.$router.getRoutes().map(route => ({
name: route.name,
path: route.path
})).filter((route) => route.name !== "Home" && route.name !== "Table of Contents")
}
},
created(){
},
data(){
return{}
}
最簡單的解決方案是:
const filteredRoutes = [
'Home',
'Table of Contents'
];
this.routes = this.routes.filter(route => !filteredRoutes.includes(route.name));
你能做這樣的事情嗎?
// Define array of unwanted routes
const unwantedRoutes = ["Home", "Table of Contents"]
export default {
data(){
return{
// Set routes to empty array
routes: []
}
},
created() {
// Get vue router routes
const routerRoutes = this.$router.getRoutes()
// Extract only routes which name is not added to the unwantedRoutes array
const wantedRoutes = routerRoutes.filter(({ name }) => !unwantedRoutes.includes(name))
// set routes to array that contains objects with only name and the path from each wanted route
this.routes = wantedRoutes.map(({ name, path }) => ({ name, path }));
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.