【问题标题】:Laravel vue won't return meta tagsLaravel vue 不会返回元标记
【发布时间】:2018-09-12 02:19:21
【问题描述】:

我在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. 如何获取动态页面(如单个帖子组件)的标题?

.......

【问题讨论】:

    标签: laravel vuejs2 meta-tags


    【解决方案1】:

    您需要添加一种在 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));
        }
    });
    

    【讨论】:

    • 谢谢,我的第二个问题?你有什么解决办法吗?
    • @mafortis 在组件中设置document.title。您可以尝试为 $route 添加一个观察者,或者如果您使用 ajax 来获取组件的数据,然后在 success/then 方法中设置它。
    • 我刚刚尝试过,但是没有用,created() { document.title = this.$route.title; document.head.querySelector('meta[name=description]').content = 'New Description'; },
    • @mafortis 不会是this.$route.meta.title 吗?你遇到了什么错误?
    • 返回未定义。
    猜你喜欢
    • 1970-01-01
    • 2019-05-21
    • 2022-09-30
    • 2019-01-25
    • 2018-12-03
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多