Nuxt Init/Entry via plugins (main.js of Vue)
February 20, 2020Fetch app configuration data before app render
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 plugins
export 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)
}
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn