首页 > 解决方案 > Laravel vue 不会返回元标记

问题描述

我在我的中提供了元,vue-router但它没有在我的 html 中返回

代码

router sample

{
            path: '/',
            name: 'home',
            component: Home,
            meta: {
                title: 'Home Page - Welcome',
                metaTags: [
                  {
                    name: 'description',
                    content: 'The home page of our example app.'
                  },
                  {
                    property: 'og:description',
                    content: 'The home page of our example app.'
                  }
                ]
            }
        },
        {
            path: '/login',
            name: 'login',
            component: Login,
            meta: { title: 'Login' }
        },

beforeeach

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (localStorage.getItem('myApp.jwt') == null) {
            next({
                path: '/login',
                params: { nextUrl: to.fullPath }
            })
        } else {
            let user = JSON.parse(localStorage.getItem('myApp.user'))
            if (to.matched.some(record => record.meta.is_admin)) {
                if (user.is_admin == 1) {
                    next()
                }
                else {
                    next({ name: 'userboard' })
                }
            }
            next()
        }
    } else {
        next()
    }
});

这是我的页头的样子:

一

并且浏览器中也没有元的迹象:

二

问题

  1. 如何解决这个问题?
  2. 如何获取单个帖子组件等动态页面的标题?

…………

标签: laravelvuejs2meta-tags

解决方案


您需要添加一种方法来更新 DOM 中的标签,因为vue-router开箱即用不会为您执行此操作。

您可以尝试添加类似以下内容的后挂钩:

router.afterEach((to, from) => {

    document.title = to.meta && to.meta.title ? to.meta.title : ''; // You can add a default here

    Array.from(document.querySelectorAll('[data-vue-meta]')).map(el => el.parentNode.removeChild(el));

    if (to.meta && to.meta.metaTags) {
        to.meta.metaTags.map(tagDef => {
            let tag = document.createElement('meta');

            Object.keys(tagDef).forEach(key => tag.setAttribute(key, tagDef[key]));

            tag.setAttribute('data-vue-meta', '');

            return tag;
        }).forEach(tag => document.head.appendChild(tag));
    }
});

推荐阅读