###### tags: `Vue` `店商網頁`
{%hackmd BJrTq20hE %}
# Vue店商網頁-建立動態標題
有沒有一種不用用套件與進入各別產品頁的時候又能把產品名稱當作標題的方法呢???
答案是有的,以下的方法完全不需要使用到額外的套件。
## 在index.js建立好meta
第一步就是建立好在Vue-cli中router這個套件所用到的index.js內的meta。如下圖

範例程式碼如下
```javascript=
{
path: '/',
name: 'Home',
component: () => import('../views/Front/FrontPage.vue'),
meta: { title: 'Home' },
children: [{
path: '',
name: 'HomeView',
component: () => import('../views/Front/HomeView.vue'),
meta: { title: 'Home' }
},
{
path: 'articles',
component: () => import('../views/Front/Articles.vue'),
meta: { title: 'article' }
}]
}
```
重點就是 meta: { title: 'TITLENAME' }
## 在main.js執行導航守衛
要記得在main.js執行以下的程式碼,不然上面的meta:{ title: 'TITLENAME'}會白打。
```javascript=
router.beforeEach((to, from, next) => {
if (to.meta.title) {
document.title = to.meta.title
}
next()
})
```
上面的程式碼重點是要記得先import router之後,放在app.use(router)之後,不然會報錯。下圖是正確示範。

## 都準備好了要怎麼改title呢?
使用document.title = 'TITLENAME'
到個別的產品頁,或是想要改標題的頁面,簡單的來說就是放在view資料夾有.vue的都能用啦。
```javascript=
methods: {
getProduct () {
this.isLoadingPage = true
const { id } = this.$route.params
this.$http.get(`${process.env.VUE_APP_API}/api/${process.env.VUE_APP_PATH}/product/${id}`).then((res) => {
this.product = res.data.product
this.isLoadingPage = false
// 修改標題,如果沒有標題就用route中index.js內建標題
document.title = this.product.title || this.$route.meta.title
})
.catch((err) => { console.dir(err.response.data.message) })
}
},
mounted () {
getProduct()
}
```
看上面範例第9行,因為要修改的資料需要透過API取得,所以我把它寫取得product.title後才修改,另外避免沒有取到product.title而報錯,所以另外用$route.meta.title取得自己在index.js所設的title。
參考資料
---
[如何在 Vue 建立動態 title](https://israynotarray.com/vue/20200530/3823952369/)
[聊聊 Vue 中 title 的動態修改](https://iter01.com/425660.html)
[Vue - 設置每頁的 title 及 圖標](https://leahlin912.github.io/2019/10/03/Vue-%E8%A8%AD%E7%BD%AE%E6%AF%8F%E9%A0%81%E7%9A%84title%E5%8F%8A%E5%9C%96%E6%A8%99/)