您的位置:

Vue3路由导航守卫:如何在网页中设置附加SEO元素

一、前言

当开发者在开发网站时,希望用户能够更好地找到自己制作的网站,并且在搜索引擎中排名更高。在这种情况下,搜索引擎优化(SEO)就显得至关重要。SEO可以通过设置一些比如 标签、标签、<link>标签等来完成。</p>

二、Vue3路由概述

Vue3是Vue.js的最新版本,它是一种渐进式JavaScript框架,拥有多个功能,包括组件化、状态管理、路由等。Vue Router是Vue.js中的官方路由库,可以帮助我们在单页面应用程序中实现基于组件的导航。

路由可以让用户在浏览器中通过点击链接、输入URL等方式进行导航。路由跳转时可以通过导航守卫来实现一些逻辑控制。路由导航守卫是Vue Router提供的一个功能,可以在路由切换时进行控制。本文将主要介绍如何在Vue3中使用路由导航守卫的功能来设置附加SEO元素。

三、设置网页标题标签</h3>

标题(title)标签是网页优化的基础,可以告诉搜索引擎要显示的信息和网页的主要内容。在Vue3中,需要使用路由导航守卫中的beforeEach方法。这个方法会在每个路由切换之前调用。

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [...]
})

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

上面的代码中,我们在beforeEach方法中设置了document.title值为to.meta.title。这里的to表示要跳转的路由信息,通过它能够访问到meta中的title属性。接下来在每个路由配置的meta中加入title字段即可。

const router = createRouter({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        title: '网站首页'
      }
    },
    ...
  ]
})

四、设置meta标签

在Vue3中,设置meta标签也可以通过使用路由导航守卫的方法beforeEach完成。可以将meta信息存储在路由配置中,然后在跳转时将其添加到网页头部中。

router.beforeEach((to, from, next) => {
  const head = document.getElementsByTagName('head')[0]
  const meta = document.createElement('meta')
  meta.content = to.meta.description || '这是一个Vue3应用程序'
  meta.name = 'description'
  head.appendChild(meta)
  next()
})

上述代码中,在beforeEach方法中,我们首先获取了head元素,然后创建了一个meta元素,并且将to.meta.description属性的值设置为了content。最后,将新的meta元素添加到head元素中。如下是路由配置中meta标签的设置:

const router = createRouter({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        title: '网站首页',
        description: '这是一个Vue3应用程序'
      }
    },
    ...
  ]
})

五、设置link标签

Link标签是一种较为复杂的meta标签,主要用于网站图标、样式表等。在Vue3中,设置Link标签也可以通过使用路由导航守卫的方法beforeEach完成。

router.beforeEach((to, from, next) => {
  const head = document.getElementsByTagName('head')[0]
  const favicon = document.querySelector('link[rel="icon"]')
  favicon.href = to.meta.icon || '/favicon.ico'
  if (!favicon) {
    const link = document.createElement('link')
    link.href = to.meta.icon || '/favicon.ico'
    link.rel = 'icon'
    head.appendChild(link)
  }
  next()
})

在上述代码中,我们首先获取了head元素和当前网站的favicon。如果favicon不存在,我们就创建了一个link元素,并且将to.meta.icon属性的值设置为href,并且将rel属性设置为icon。接着我们将新link元素添加到head元素中。如下是路由配置中link标签的设置:

const router = createRouter({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      meta: {
        title: '网站首页',
        description: '这是一个Vue3应用程序',
        icon: '/favicon.ico'
      }
    },
    ...
  ]
})

六、小结

通过本文的介绍,我们可以了解如何在Vue3中使用路由导航守卫的功能来设置附加SEO元素。包括设置标签、 标签、<link>标签等。这些元素都可以对网站的优化起到重要的作用。

Vue3路由导航守卫:如何在网页中设置附加SEO元素

2023-05-17
路由导航守卫

2023-05-20
如何让Vue路由的beforeEach钩子对网页权重产生积极

2023-05-16
Vue子路由跳转详解

2023-05-19
详解Vue3 beforeeach

2023-05-23
Vue3和Vue-Router的全方位探索

2023-05-21
React路由守卫详解

2023-05-21
Uniapp路由守卫实现页面访问权限控制

2023-05-17
编程式导航

2023-05-20
Vue路由权限详解

2023-05-21
Vue Router 4的完整使用教程

2023-05-23
探究route.push - Vue路由实现页面跳转

2023-05-23
Vue Router 4 导航故障

2023-05-16
vuewatch路由详解

2023-05-19
Vue路由钩子详解

2023-05-21
when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${item.id} [in template "article/detail/index.ftl" at line 48, column 106] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:104) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:371) at freemarker.core.IteratorBlock$IterationContext.executedNestedContentForCollOrSeqListing(IteratorBlock.java:321) at freemarker.core.IteratorBlock$IterationContext.executeNestedContent(IteratorBlock.java:271) at freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:244) at freemarker.core.Environment.visitIteratorBlock(Environment.java:645) at freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:108) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:94) at freemarker.core.Environment.visit(Environment.java:335) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.process(Environment.java:314) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:332) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:266) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:220) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:181) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1431) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1167) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1106) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at com.software.filter.HttpSpiderIdentifyFilter.doFilter(HttpSpiderIdentifyFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at java.base/java.lang.VirtualThread.run(VirtualThread.java:309)