前言 以往我們在複製貼上網址時,都會有一些描述與標題,在原本的 SPA 下是不會有這個功能,永遠都只能保持預設的 head,那 Nuxt.js 該如何做到呢?所以接下來就要聊聊 head 的設定。
Head Setting head 是非常重要的設置,畢竟 SPA 模式下總是都是固定頁面且無法設置,例如我之前做的作品 RagnarokShopV3 中雖然我有設定 head
但這個 head 是全站式的。
什麼意思呢?通常我們切換到哪一個頁面就會顯示相對應的 head,例如產品頁面,那 head 可能會是這樣
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <head > <meta charset ="utf-8" > <meta http-equiv ="X-UA-Compatible" content ="IE=edge" > <meta name ="viewport" content ="width=device-width,initial-scale=1.0" > <meta name ="keywords" content ="RagnarokShop 商店, RagnarokShop, 產品頁面" /> <meta name ="description" content ="Vue 出一個 RagnarokShop 產品頁面" > <meta property ="og:type" content ="website" > <meta property ="og:title" content ="RagnarokShop" > <meta property ="og:url" content ="/RagnarokShopV3/#/" > <meta property ="og:description" content ="RagnarokShop 產品頁面" > <meta property ="og:image" content ="https://tro.gnjoy.com.tw/Content/Event/20200505_expansion185/img/1200x628.jpg" > <meta property ="og:site_name" content ="RagnarokShop" > <meta property ="og:locale" content ="zh_TW" > <link rel ="icon" href ="<%= BASE_URL %>favicon.ico" > <title > 產品頁面 - RagnarokShopV3</title > </head >
而這個設置對於 SEO 來講是非常重要的,因為搜尋引擎爬蟲往往會透過這些設置了解你當前頁面有什麼,簡單來講類似精髓重點摘要,所以為了解決這個問題 Nuxt.js 的 head 就顯得格外重要。
那麼在 Nuxt.js 中又區分為 Global 跟 Local 設置,因此這一點必須多加注意一下。
Global Head Global Head 簡單來講就是預設的 head,當頁面沒有特別設置的話,那麼就會一率套用 Global 設置。
那麼該如何設定呢?基本上就是在 nuxt.config.js 中設定
基本上如果你有打開過的話,你應該會看到官方預設的內容
你可以試著將 title 改一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 export default { head : { title : 'Nuxt 示範檔案' , htmlAttrs : { lang : 'en' }, meta : [ { charset : 'utf-8' }, { name : 'viewport' , content : 'width=device-width, initial-scale=1' }, { hid : 'description' , name : 'description' , content : '' }, { name : 'format-detection' , content : 'telephone=no' } ], link : [ { rel : 'icon' , type : 'image/x-icon' , href : '/favicon.ico' } ] }, }
接下來你執行 npn run dev 之後就可以看到抬頭一率改成了 Nuxt 示範檔案
Local Head 但是我們不可能全部頁面 head 都是一樣的,舉例來講關於我們的頁面 title 可能會是「關於我們 - Nuxt 示範檔案」,那該怎麼設置呢?其實非常簡單。
打開 About.vue 檔案之後,在底下加入 head 屬性跟相關設置就可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <template> <div> <p> 是 Ray 不是 Array http://israynotarray.com </p> </div> </template> <script> export default { head: { title: '關於我們 - Nuxt 示範檔案' } } </script>
透過該設定,我們可以在特定的頁面中給予特定的 head。
當然也可以調整 meta 相關設置,這邊我就直接貼上官方範例
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 <template> <h1>{{ title }}</h1> </template> <script> export default { data() { return { title: 'Hello World!' } }, head() { return { title: this.title, meta: [ // hid is used as unique identifier. Do not use `vmid` for it as it will not work { hid: 'description', name: 'description', content: 'My custom description' } ] } } } </script>
參考文獻
整理這些技術筆記真的很花時間,如果你願意 關閉 Adblock 支持我,我會把這份感謝轉換成更多「踩坑轉避坑」的內容給你!ヽ(・∀・)ノ
Advertisement