简体   繁体   中英

How to add meta in nuxt router?

In vue, we defined meta like this:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

But how do we define meta in nuxt?

I built a Nuxt module that basically injects page variables into the route.meta property at build time. Then you can use it inside this.extendRoutes or to generate sitemap routes with @nuxtjs/sitemap .

Install it via npm install nuxt-route-meta and add it to your nuxt.config.js :

// nuxt.config.js

export default {
  modules: [
    'nuxt-route-meta',
  ],
}

Add meta properties in a page:

export default {
  auth: true,
  meta: {
    theme: 'water',
  },
}

And now you have the properties in route.meta in each route. You can for example check it by using this.extendRoutes inside a module:

export default function () {
  this.extendRoutes(routes =>
    routes.forEach(route => {
      if (route.meta.auth) {
        // do something with auth routes
      }
    })
  )
}

You can add to the page you want the meta data to be rendered in. Inside you page you put

export default {
  head() {
    return {
      title: 'My Page title',
    }
  },
  data() { ... }
}

see - https://nuxtjs.org/api/pages-head

If you'd like to have all pages share some values you can place meta info in your nuxt.config.js like so

module.exports = {
  head: {
    htmlAttrs: {
      lang: 'EN'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'marketing website' },
      { name: 'theme-color', content: '#0394da' }
    ]
  }
}

see - https://nuxtjs.org/api/configuration-head

for list of all meta attributes go here https://github.com/declandewet/vue-meta

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM