功能-实现面包屑导航

本文介绍了如何在Vue.js应用中实现面包屑导航,包括获取当前页面路由、配置router、创建列表div以及使用js处理样式和路由跳转逻辑。重点讲解了`this.$router`的相关属性和方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现逻辑

1、获取当前页面的路由列表存储到bread List中

2、页面展现breadList列表内容

3、列表样式分为是否是当前页面和非当前页面,根据路由情况设置样式

4、只有当点击否当前路径时才执行条转逻辑

router路由的配置

{
	path: "/",
	// name: "home",
	component: home,
	meta: { title: "首页" },
	children: [
		{
			path: "/",
			name:'home',
			components: {
				pageContent: index,
			},
		},
		{
			path: "content",
			name: "content",
			components: {
				pageContent: content,
			},
			meta: { title: "内容" },
		},
		{
			path: "like",
			name: "like",
			components: {
				pageContent: like,
			},
			meta: { title: "收藏" },
		},
		{
			path: "nolike",
			name: "nolike",
			components: {
				pageContent: nolike,
			},
			meta: { title: "不喜欢" },
		},
	],
},

列表div

<div class="navigationList">
	<div class="item" v-for="(item, index) in breadList" :key="index">
		<div
			@click="toPath(item.name)"
			:class="isNowPath(item.name) ? 'nowPath' : 'unchecked'"
		>
			{{ item.meta.title }}
			<span
				style="color: #e7d6d6; margin: 0 5px"
				v-if="index < breadList.length - 1 && $router.currentRoute.path != '/'"
				>></span
			>
		</div>
	</div>
</div>

js部分

data() {
	return {
		breadList: [],
	};
},
watch: {
	$route(to, from) {
		this.breadList = to.matched;
	},
},
methods: {
	// 点击按钮跳转到首页
	toPath(pathname) {
		const route = this.$router.options.routes[0].children.find(
			r => r.name === pathname || r.path === ""
		);
		if (route) {
			if (!this.isNowPath(route.name)) {
				this.$router.push({ name: route.name });
			}
		} else {
			console.error(`Route with name "${routeName}" not found.`);
		}
	},
	//获取当前路由的名称
	getRouterName() {
		let routerList = this.$route.matched;
		routerList[0].path = "/";
		routerList[0].name = "home";
		this.breadList = routerList;
	},
	isHome(name) {
		return name === "home";
	},
	isNowPath(name) {
		return name === this.$router.currentRoute.name;
	},
},
mounted() {
	this.getRouterName();
},

小知识

this.$router   的部分属性

属性名说明

currentRoute

存储当前路径的内容

options

提供的选择

options.routes

可以选择的路由配配置

this.$router  的方法

方法

说明
push进行跳转参数{key:value}

更多内容 | Vue Router

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

煦炎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值