You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue3原生Router中实现动态Meta标签?

Vue3 原生 Router 实现动态 Meta 标签方案

一、在路由配置中定义元数据字段

直接在路由规则的meta属性里,为每个页面配置对应的SEO元数据(标题、描述、关键词等),静态页面可直接写死,动态页面可先设默认值,后续在组件内更新。

示例(router/index.js):

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页 - 我的Vue3网站',
      description: '这是我的Vue3网站首页,提供XX服务与内容',
      keywords: 'Vue3, SEO, 动态Meta'
    }
  },
  {
    path: '/article/:id',
    name: 'Article',
    component: () => import('../views/Article.vue'),
    meta: {
      title: '文章详情',
      description: ''
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

二、全局路由守卫统一更新静态Meta

利用路由的afterEach钩子,在每次路由切换完成后,自动更新页面标题和基础Meta标签。

在router/index.js中添加:

router.afterEach((to) => {
  // 更新页面标题
  document.title = to.meta.title || '默认网站标题'
  
  // 更新description标签
  const descEl = document.querySelector('meta[name="description"]')
  if (descEl && to.meta.description) {
    descEl.setAttribute('content', to.meta.description)
  }
  
  // 更新keywords标签
  const keywordsEl = document.querySelector('meta[name="keywords"]')
  if (keywordsEl && to.meta.keywords) {
    keywordsEl.setAttribute('content', to.meta.keywords)
  }
})

三、处理异步数据的动态Meta

对于需要根据接口返回数据更新Meta的页面(比如文章详情页),在组件内通过onMounted和路由参数监听来更新。

示例(Article.vue):

import { onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'

// 模拟异步获取文章数据的函数
const fetchArticleById = async (id) => {
  // 实际替换为你的接口请求逻辑
  return await fetch(`/api/article/${id}`).then(res => res.json())
}

export default {
  setup() {
    const route = useRoute()

    // 页面初始化时更新Meta
    const updateArticleMeta = async (id) => {
      const article = await fetchArticleById(id)
      document.title = `${article.title} - 我的Vue3网站`
      
      const descEl = document.querySelector('meta[name="description"]')
      if (descEl) {
        descEl.setAttribute('content', article.summary)
      }
      
      // 如需更新Open Graph标签,同理处理
      const ogTitleEl = document.querySelector('meta[property="og:title"]')
      if (ogTitleEl) {
        ogTitleEl.setAttribute('content', article.title)
      }
    }

    onMounted(() => {
      updateArticleMeta(route.params.id)
    })

    // 监听路由参数变化(同页面切换不同文章)
    watch(() => route.params.id, (newId) => {
      updateArticleMeta(newId)
    })

    return {}
  }
}

四、基础准备

确保public/index.html中已包含基础Meta标签,方便后续修改:

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <!-- Open Graph 标签(如需) -->
  <meta property="og:title" content="">
  <meta property="og:description" content="">
  <title>默认标题</title>
</head>

内容的提问来源于stack exchange,提问作者griff4594

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:10:25