fncheng / vue-learn

0 stars 0 forks source link

浏览器title动态修改 #18

Open fncheng opened 3 years ago

fncheng commented 3 years ago
/**
 * 获取title
 * @param {String} vm VueComponent实例
 * @returns $route.meata.title
 */
const getTitle = (vm) => {
  const { title } = vm.$options
  if (title) {
    return typeof title === 'function' ? title.call(vm) : title
  } else {
    return vm.$route?.meta?.title || ''
  }
}

const globalMixin = {
  mounted() {
    // 浏览器title动态修改
    const title = getTitle(this)
    if (title) {
      document.title = title
    }
  },
}
export default globalMixin

思路是 在路由表routes中meta属性定义一个title,然后在每个页面的mounted阶段获取$route.meta.title,之后修改document.title。而需要在每个页面的mounted阶段都运行,可以使用全局mixin。