vue2+element-ui实现网站标题随着路由改变动态切换标题

发布时间 2023-04-04 00:26:51作者: Amyel

以下内容仅供自己学习使用

1. 效果图

image

2. 第一步在router.js编写meta:{title:''}

image

3. 然后挂载路由导航守卫

// 在Vue实例创建之前获取路由信息
router.beforeEach((to, from, next) => {
  // 更新动态标题
  document.title = to.meta.title || 'Vue2-Admin'
  next()
})
  1. 去/public/index.html页面
    4.1 在data里面默认定义一个title
    title: 'Vue2-Admin'

image

4.2 使用 created 钩子函数来设置初始标题

   created: function () {
      if (this.$route && this.$route.meta && this.$route.meta.title) {
        this.title = ' - Vue2-Admin' + this.$route.meta.title;
      }
    },

4.3 使用计算属性 titleComputed 来动态计算标题,

  computed: {
      titleComputed: function () {
        if (this.$route && this.$route.meta && this.$route.meta.title) {
          return this.title = ' - Vue2-Admin' + this.$route.meta.title;
        } else {
          return this.title;
        }
      }
    },

4.4 使用 watch 来监听路由变化并更新标题。

 watch: {
      '$route': function () {
        this.title = this.titleComputed;
      }
    }

4.5 这样初始标题就会在页面加载时立即显示,并且不会出现{{title}}闪烁问题。

  1. 完整的页面代码
<!DOCTYPE html>
<html lang="">

<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">
  <link rel="icon" href="<%= BASE_URL %>logo.5ac24feb.ico">
  <title>{{ title }}</title> <!-- 动态的标题 -->
</head>

<body>
  <noscript>
    <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
</body>

<script>
  var app = new Vue({
    el: '#app',
    data: {
      title: 'Vue2-Admin'
    },
    created: function () {
      if (this.$route && this.$route.meta && this.$route.meta.title) {
        this.title = ' - Vue2-Admin' + this.$route.meta.title;
      }
    },
    computed: {
      titleComputed: function () {
        if (this.$route && this.$route.meta && this.$route.meta.title) {
          return this.title = ' - Vue2-Admin' + this.$route.meta.title;
        } else {
          return this.title;
        }
      }
    },
    watch: {
      '$route': function () {
        this.title = this.titleComputed;
      }
    }
  });
</script>

</html>