mafortis
mafortis

Reputation: 7128

Laravel vue won't return meta tags

I provided meta in my vue-router but it doesn't return in my html

Code

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()
    }
});

This is how my page head is look like:

one

and no sign of meta in browser as well:

two

Questions

  1. How to fix this issue?
  2. How can I get title for dynamic pages like single post components?

..........

Upvotes: 0

Views: 1400

Answers (1)

Rwd
Rwd

Reputation: 35180

You would need to add a way for the tags to be updated in the DOM as vue-router won't do this for you out-of-the-box.

You could try adding an after hook with something like:

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));
    }
});

Upvotes: 1

Related Questions