Vue_ 自訂圖標及標題

Vue Router 設置每頁 title

通常網站不僅有一個網頁,建議每個網頁應當有一個專屬的title,以便管理

step0.在自己專案中的 router.js 或 router/index.js 檔案中(依照個人在專案中的檔案命名及路徑),確定有引入 vue 及 vue-router

1
2
3
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

step1. 加入每個路徑頁面的 meta 資料,且於meta中定義title文字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

const router = new VueRouter({
routes: [
{
path: '/entrance',
name: 'entrance',
component: Entrance,
meta: {
title: 'Entrance'}
},{
path: '/login',
name: 'login',
component: Login,
meta: {
title: 'Login'}
},{
path: '/test',
name: 'test',
component: Test,
meta: {
title: 'Test'}
}]
})

step2.使用全域 navigation guards 非同步解析執行:當路徑(router object)前往(to) meta.title 時,瀏覽器的 title 為 meta.title

1
2
3
4
5
6
7

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

step3.最後引出該 router

1
export default router;

在 vue 專案中變更 title 圖示

step1.因為專案會使用 webpack 或 vue-cli 打包,因此將圖片放置根目錄,或是static資料夾中
step2.在 html 的 中配置圖片及文字。

1
2
3
4
5
6

<head>
<title>標題文字</title>
<!--href中的路徑依照專案實際放置圖示的位置。-->
<link rel="icon" href="./../static/favicon.ico" type=“image/x-icon>
</head>

step3.修改 webpack 配置檔案

1
2
3
4
5
new HtmlWebpackPlugin({
//...
favicon: path.resolve('/static/favicon.ico'), //路徑依照專案實際放置圖示的位置
//...
})

step4.重新啟用,並適時清除瀏覽器暫存資料,即可正確圖示畫面