為 Vue 加上網站標題與描述

使用 router beforeEach 設定網站標題

在 Vue CLI 中的 router/index.js 中設定網站標題

  1. 在所有路由中添加 meta 欄位,定義網站標題:

    1
    2
    3
    meta: {
    title: '網站標題',
    }
  2. router 設定的最下方,加入以下程式碼以更新標題:

    1
    2
    3
    4
    5
    6
    router.beforeEach((to, from, next) => {
    if (to.meta.title) {
    document.title = to.meta.title;
    }
    next();
    });

完整範例

以下是設定的完整範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import Vue from 'vue';
import VueRouter from 'vue-router';

const routes = [
{
path: '/',
name: 'Layout',
component: () => import('../views/frontend/Layout.vue'),
children: [
{
path: '',
name: 'index',
meta: {
title: '首頁',
},
component: () => import('../views/frontend/index.vue'),
},
{
path: 'about',
name: '關於我',
meta: {
title: '關於我',
},
component: () => import('../views/frontend/About.vue'),
},
{
path: 'products',
name: '全部產品',
meta: {
title: '所有產品',
},
component: () => import('../views/frontend/Products.vue'),
},
],
},
{
path: '*',
redirect: '/',
},
];

const router = new VueRouter({
routes,
});

router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title;
}
next();
});

export default router;

使用 vue-meta

vue-meta 是一個用於管理 Vue 應用中的元數據的插件,可以輕鬆地在每個組件中設定和更新頁面的 meta 標籤。這對於 SEO 來說非常重要,因為它有助於提高頁面的可見性。

安裝 vue-meta

首先,您需要安裝 vue-meta

1
npm install vue-meta

在 Vue 中使用 vue-meta

  1. main.js 中引入並使用 vue-meta

    1
    2
    3
    4
    import Vue from 'vue';
    import VueMeta from 'vue-meta';

    Vue.use(VueMeta);
  2. 在每個需要設定 meta 的組件中,新增 metaInfo 屬性:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    export default {
    metaInfo: {
    title: '特定頁面的標題',
    meta: [
    { name: 'description', content: '這是特定頁面的描述' },
    { name: 'keywords', content: '關鍵字1, 關鍵字2' },
    ],
    },
    };

組件範例

以下是一個使用 vue-meta 的組件範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div>
<h1>歡迎來到我們的網站</h1>
<p>這是關於我們的頁面。</p>
</div>
</template>

<script>
export default {
metaInfo: {
title: '關於我們',
meta: [
{ name: 'description', content: '這是關於我們的頁面,介紹了我們的使命和願景。' },
],
},
};
</script>

小結

  1. router.beforeEach

    • 功能:主要用於全局路由守衛,可根據路由元數據更新頁面標題。
    • 優點:簡單易用,適合小型專案或不需要複雜 meta 管理的情況。
    • 缺點:只能設置基本的 document.title,無法管理其他 meta 標籤。
  2. vue-meta

    • 功能:專門用於管理 Vue 應用中的所有元數據,包括標題、描述、關鍵字等。
    • 優點:提供靈活性,可針對每個組件自定義 meta 信息,適合 SEO 優化。
    • 缺點:稍微複雜,需額外安裝和配置。

如果您的專案較小,且只需要基本的標題管理,使用 router.beforeEach 會更簡單直接。

如果您希望針對每個頁面進行更細緻的 SEO 優化,建議使用 vue-meta