You need to setup a plugin for initialization.
Edit nuxt.config.js
.
export default { plugins: [ '~/plugins/init' ]}
You can setup run specific code on client and server
export default { plugins: [ '~/plugins/init', // run on both client and server { src: '~/plugins/init-client', mode: 'client' }, { src: '~/plugins/init-server', mode: 'server' } ]}
Edit plugins/init.js
.
- You can inject global functions or variables
- You can detect client, server or static environment variable
- You can setup Vue.js plugins
import Vue from 'vue'if (process.server) { // do something if (process.static) { // do something }}if (process.client) { // do something}// Vue.prototype.$hello = ...// OPTIONAL: access other pluginsexport default sync ({ app, $axios, store }, inject) => { // access object injected by other plugins // app.$test.ping() // inject something // inject('hello', ...) // fetch configuration data before render let data = null if (process.server) { // read local file if server const fs = require('fs') data = JSON.parse(fs.readFileSync(`static/data/config.json`, 'utf8')) } else if (process.client) { // ajax fetch if client data = await $axios.get(`/data/config.json`) } // commit to vuex store store.commit('config', data)}