How to hide sidebar navigation if there is only a single item

Category:
Tags:
Last Updated: 2021/12/13 12:40:54

In VuePress, sidebar navigation is automatically rendered from the header elements in page content. Usually this is useful, however, when there is just a single item, I feel there is no need for this navigation, so I hid this navigation with just one item.

Items in sidebar navigation come from sidebarItems method defined within computed in themes/layouts/Layout.vue.

export default {
	computed: {
		sidebarItems () {
			return resolveSidebarItems(
				this.$page,
				this.$page.regularPath,
				this.$site,
				this.$localePath
			);
		},
	}
};

1
2
3
4
5
6
7
8
9
10
11
12
13

resolveSidebarItems method is defined in themes/util/index.js, but because changing themes/util/index.js may affect other parts, We will update this sidebarItems method.

export default {
	computed: {
		sidebarItems () {
			const items = resolveSidebarItems(
				this.$page,
				this.$page.regularPath,
				this.$site,
				this.$localePath
			);
			if (items.length > 1) return items;
			if (items.length <= 0) return [];
			if (! items[0].children || items[0].children.length <= 0) return [];
			return items;
		},
	}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

After this change, sidebar navigation is hidden when there is only one item.

... But there may be one problem. If there is only one item, sidebar itself is hidden. In this site's case, there are also tags and categories in the sidebar, so the sidebar have to be visible even when navigation is hidden.

The solutions for this is shouldShowSidebar method, which is also defined in computed in themes/layouts/Layout.vue. This method returns boolean and if you want to always show sidebar, you can write return true.

export default {
	computed: {
		shouldShowSidebar () {
			return true;
		},
	}
};
1
2
3
4
5
6
7

Category:
Tags:
Last Updated: 2021/12/13 12:40:54
Copyright © Web Ninja All Rights Reserved.