Nuxt.JS Plugin

From WikiOD

Nuxt.js allows you to execute js plugins before running Vue.js applications. This is especially useful when you need to use your own libraries or third-party modules.

It should be noted that in the life cycle of any Vue component , only the two methods before Create and created will be called on the client and server. Other life cycle functions are only called on the client side.

Use third-party modules[edit | edit source]

We can use third-party modules in our applications. A typical example is to use axios to  make HTTP requests on the client and server  .

First we need to install the npm package:

npm install --save axios

Then, use it like this in the page:

<template>
 <nowiki> </nowiki> <nowiki><h1>{{ title }}</nowiki><nowiki></h1></nowiki>
 </template>
 
 <nowiki><script>
 import axios from 'axios'
 
 export default {
   async asyncData ({ params }) {
     let { data } = await axios.get(`https://my-api/posts/${params.id}`</nowiki>)
 <nowiki> </nowiki>   return { title: data.title }
 <nowiki> </nowiki> }
 }
 <nowiki></script></nowiki>
Use Vue plugin[edit | edit source]

If we want to use  vue-notifications to  display application notification information, we need to configure this plugin before the program runs.

First add the file plugins/vue-notifications.js:

import Vue from 'vue'
 import VueNotifications from 'vue-notifications'
 
 Vue.use(VueNotifications)

Then, configure plugins in nuxt.config.js as follows:

module.exports = {
   plugins: ['~/plugins/vue-notifications']
 }

To learn more about the configuration of plugins, please refer to the  plugin API documentation .

ES6 plugin[edit | edit source]

If the plugin is located in node_modules and exports the module, it needs to be added to the transpile build options:

module.exports = {
   build: {
     transpile: ['vue-notifications']
   }
 }

You can refer to the  build configuration  documentation for more build options.

Inject $rot and context[edit | edit source]

Sometimes you want to use a certain function or property value in the entire application. At this time, you need to inject them into the Vue instance (client), context (server) or even store (Vuex). By convention, newly added property or method names use $ as a prefix.

Inject Vue instance[edit | edit source]

Inject the content into the Vue instance to avoid repeated introduction, mount and inject a function on the Vue prototype, which can be accessed in all components (not including the server-side).

plugins / vue-inject.js:

im

port Vue from 'vue'
 
 Vue.prototype.$myInjectedFunction = string => console.log('This is an example', string)

nuxt.config.js:

export default {
   plugins: ['~/plugins/vue-inject.js']
 }

In this way, you can use the function in all Vue components.

example-component.vue:

export default {
   mounted () {
     this.$myInjectedFunction('test')
   }
 }
Inject context[edit | edit source]

The context injection method is similar to injecting in other vue applications.

plugins/ctx-inject.js:

export default ({ app }, inject) => {
   // Set the function directly on the context.app object
   app.myInjectedFunction = string => console.log('Okay, another function', string)
 }

nuxt.config.js:

export default {
  plugins: ['~/plugins/ctx-inject.js']
}

Now, as long as you get the context, you can use the function (for example, in asyncData and fetch). ctx-example-component.vue:

export default {
   asyncData (context) {
     context.app.myInjectedFunction('ctx!')
   }
 }
Simultaneous injection[edit | edit source]

If you need to inject in context, Vue instance, or even Vuex at the same time, you can use the inject method, which is the second parameter of the plugin export function. The method of injecting content into a Vue instance is similar to injecting in a Vue application. The system will automatically add $ to the front of the method name.

plugins/combined-inject.js:

export default ({ app }, inject) => {
  inject('myInjectedFunction', string => console.log('That was easy!', string))
}

nuxt.config.js:

export default {
  plugins: ['~/plugins/combined-inject.js']
}

Now you can call the myInjected Function method in the context, or this in the Vue instance, or this in the actions/mutations method of Vuex. ctx-example-component.vue:

export default {
   mounted () {
     this.$myInjectedFunction('works in mounted')
   },
   asyncData (context) {
     context.app.$myInjectedFunction('works with context')
   }
 }

store/index.js:
 <syntaxhighlight lang="js">
export const state = () => ({
 <nowiki> </nowiki> someValue: <nowiki>''</nowiki>
 })
export const mutations = {
  changeSomeValue (state, newValue) {
    this.$myInjectedFunction('accessible in mutations')
    state.someValue = newValue
  }
}

export const actions = {
  setSomeValueToWhatever ({ commit }) {
    this.$myInjectedFunction('accessible in actions')
    const newValue = 'whatever'
    commit('changeSomeValue', newValue)
  }
}

</syntaxhighlight>

Plug-ins used only on the client side[edit | edit source]

For systems that do not support ssr, the plug-in is only used in the browser. In this case, you can use ssr: false to make the plug-in only run on the client.

for example:

nuxt.config.js:

module.exports = {
   plugins: [
     { src: '~/plugins/vue-notifications', ssr: false }
   ]
 }

plugins/vue-notifications.js:

import Vue from 'vue'
 import VueNotifications from 'vue-notifications'
 
 Vue.use(VueNotifications)

You can control certain script libraries in the plug-in to be used only on the server side by detecting the variable process. server. When the value is true, it means that the current execution environment is in the server. In addition, you can determine whether the application is generated by a nuxt generator by checking whether process. static is true. You can also combine the two options of process. server and process. static to make sure that the current status is server-side rendering and run with the nuxt generate command.

Note: Since Nuxt.js 2.4, mode has been introduced as a plugin option to specify the plugin type, possible values ​​are: client or server, ssr: false will be deprecated in the next major version and will transition to mode: 'client'.

example:

nuxt.config.js:

export default {
   plugins: [
     { src: '~/plugins/both-sides.js' },
     { src: '~/plugins/client-only.js', mode: 'client' },
     { src: '~/plugins/server-only.js', mode: 'server' }
   ]
 }
Traditional naming plugin[edit | edit source]

If it is assumed that the plug-in only runs on the client or server, then .client.js or .server.js can be used as the extension of the plug-in file, and the file will be automatically included on the corresponding client or server.

example:

nuxt.config.js:

export default {
   plugins: [
     '~/plugins/foo.client.js', // only in client side
     '~/plugins/bar.server.js', // only in server side
     '~/plugins/baz.js' // both client & server
   ]
 }