Nuxt.js Mixin – access global property in template

Adding a mixin in nuxt.js is just like adding a plugin. For my project, I needed a date format property set once but accessible in all my templates (named ‘moment_format’)

Step 1, In plugins/, create a plugin file (Mine is called ‘vue-format-global.js)

// plugins/vue-format-global.js
import Vue from 'vue'

var mixin = {
  data: function () {
    return {
      moment_format: 'DD/MM/YYYY HH:mm'
    }
  }
}

Vue.mixin(mixin)

Step 2, connect up the plugin in nuxt.config.js

  // in nuxt.config.js

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    /* other plugins ... */
    '~/plugins/vue-format-global'
  ],

Step 3, restart the app and use freely in your templates.

// inside a template
<template>
effective since {{data.effective_date | moment(moment_format)}}
</template>