Vue.js实现:在[slug].vue页面同时展示博客列表内容
复用博客列表组件的几种实用方案
一、用RouterView v-slot实现路由嵌套(最推荐)
既然你的两个页面都属于Blog路由下的内容,直接把Blog改成父路由组件,把博客列表放在父组件里,子路由通过RouterView渲染具体页面内容即可,完全避免重复代码。
操作步骤:
- 调整路由配置
const routes = [ { path: '/blog', // 新增父组件,用来承载博客列表和子页面 component: () => import('@/pages/Blog/BlogLayout.vue'), children: [ { path: '', component: () => import('@/pages/Blog/index.vue') }, // 原博客列表页 { path: ':slug', component: () => import('@/pages/Blog/[slug].vue') } // 原单篇博客页 ] } ]
- 编写父组件
BlogLayout.vue
<template> <div class="blog-wrapper"> <!-- 只需要在这里写一次博客列表组件 --> <BlogList /> <!-- 子页面的内容会通过RouterView渲染在这里 --> <RouterView /> </div> </template> <script setup> import BlogList from '@/components/BlogList.vue' </script>
这样不管访问/blog还是/blog/xxx,都会自动显示博客列表,同时渲染对应的子页面内容,彻底告别重复调用。
二、封装独立布局组件
如果不想改动路由结构,可以把博客列表封装成布局组件的一部分,然后在两个页面中复用这个布局。
操作步骤:
- 创建布局组件
BlogWithListLayout.vue
<template> <div> <BlogList /> <!-- 插槽用来放置每个页面的自定义内容 --> <slot></slot> </div> </template> <script setup> import BlogList from '@/components/BlogList.vue' </script>
- 在页面中使用布局
在index.vue和[slug].vue里,用布局组件包裹原有内容:
<template> <BlogWithListLayout> <!-- 这里放原页面的内容 --> </BlogWithListLayout> </template> <script setup> import BlogWithListLayout from '@/layouts/BlogWithListLayout.vue' </script>
这种方式比手动重复调用组件简洁很多,只是需要在每个页面引入布局。
三、路由元信息+全局混入(适合复杂场景)
如果需要更灵活的显示控制(比如部分页面显示列表,部分不显示),可以用路由元信息标记,再通过全局混入动态渲染组件,不过这种方式维护成本稍高,非必要不推荐。
操作步骤:
- 路由配置添加元信息
const routes = [ { path: '/blog', component: () => import('@/pages/Blog/index.vue'), meta: { showBlogList: true } }, { path: '/blog/:slug', component: () => import('@/pages/Blog/[slug].vue'), meta: { showBlogList: true } } ]
- 全局混入动态挂载组件
app.mixin({ mounted() { if (this.$route.meta.showBlogList) { // 动态创建并挂载博客列表组件到页面指定容器 const BlogList = defineAsyncComponent(() => import('@/components/BlogList.vue')) createApp(BlogList).mount('#blog-list-container') } } })
需要注意的是,每个页面里要提前准备好id="blog-list-container"的DOM容器。
内容的提问来源于stack exchange,提问作者Den Pat
相关产品推荐
相关产品推荐

