Nuxt.js: [docs] What does inject do?

Created on 24 Nov 2017  路  16Comments  路  Source: nuxt/nuxt.js

In docs, inject goes unused:

export default ({ app }, inject) => {
  // Set `i18n` instance on `app`
  // This way we can use it in middleware and pages `asyncData`/`fetch`
  app.i18n = new VueI18n({
    /* `VueI18n` options... */
  })
}
however, it is named in the function signature.

Relese notes for v1.0.0-rc3 say a previous version called injectAs was removed:

  • injectAs has been removed in plugins, you can inject your plugins by accessing app (see example)

It is reintroduced as inject in v1.0.0-rc7

This version is only actually used in one file which is not featured in the examples on the site:
https://github.com/nuxt/nuxt.js/blob/ffe1b6d8dc092f22b45b765f296b0700fd05eae9/examples/with-cookies/plugins/cookies.js#L19

In v1.0.0-rc11 it currently works.

Question

When to use context.app.x = vs inject('x',?

This question is available on Nuxt.js community (#c1961)
documentation

Most helpful comment

Thank you for your support of Nuxt.js. 馃樃
inject is used for add plugin onto both Vue instance and Nuxt app.

inject('cookies', new Vue({
  // ...
}))

Through inject, you can use:

  1. app.$cookies
  2. this.$cookies in vue components
  3. this.$cookies in store actions/mutations

The documentation is exactly not clear, we will fix it soon.

All 16 comments

Thank you for your support of Nuxt.js. 馃樃
inject is used for add plugin onto both Vue instance and Nuxt app.

inject('cookies', new Vue({
  // ...
}))

Through inject, you can use:

  1. app.$cookies
  2. this.$cookies in vue components
  3. this.$cookies in store actions/mutations

The documentation is exactly not clear, we will fix it soon.

Yes, I have seen the inject code as well as that nice comment in cookies image
So they are basically mutually exclusive/redundant.
IMO there should be an exhaustive explanation of where and how app can be accessed, whether app.i18n or app.$cookies. Although that's a stock Vue concern, one of nuxt's expressed niches is baby's first Vue and that would certainly help.

PS: I don't support Nuxt, why are you saying I do? :scream: :scream_cat:

I think @clarkdo meant thanks for showing support by raising an important flag in the missing inject documentation. Raising an issue shows support, so thank you as well :)

@qm3ster your comment sounds really funny now. As they say, you never know. :laughing:

Anyway this seems to be resolved now. Closing.

Here is doc
https://nuxtjs.org/guide/plugins#inject-in-root-amp-context

That example does not show usage of inject, nor does it explain its benefits versus shoving stuff onto Vue or app.

@frankier the only difference/benefit I see is convenience. You don't have to import Vue to get the plugin in your components. this.$myPlugin has it in all components and store actions.

It also does the correct thing with regards to vuex, depending on whether it's installed not. This should all be in the docs.

@frankier you should make a PR to https://github.com/nuxt/docs

Perhaps the web worker example is a good start?

The doc you linked is found quite easily @dotnetCarpenter, but as @frankier pointed out, it does not show the usage of inject. It's not even so much the advantages it brings imo, just how to use it. Despite it being a parameter, I was very confused by it not actually being called in the example. It would be nice if somebody who knows what they're doing, could make the docs more clear in that regard.

Update the doc to show the usage of inject would help many people like me!!

@clarkdo the inject function let you use the plugin inside the actions/mutations what about the getters. I have a use case where I'd like to use mu plugin inside a getter but I can't since this is undefined, which kind of solution would you use?

@marco-gattelli
Can you provide a repo or show me your codes ?

Of course I can @clarkdo
The following is my plugin:

import ColorService from '../services/ColorService';

export default (context, inject) => {
  const colorService = new ColorService();
  inject('colorService', colorService);
};

And this is my getter inside a module:

import { productGridGetters } from './store-types';
import cloneDeep from 'lodash.clonedeep';

export default {
[productGridGetters.GET_FILTERED_PRODUCTS]: function (state, getters, rootState) {
let arrayToFilter = cloneDeep(rootState.products.currentList);
if (filter.colors.length > 0) {
      console.log(this); // *this* is undefined
      // console.log(this.$colorService); // cannot find $colorService of undefined 
      const colorsSelected = filter.colors.map(color => `${color.code}`);
      arrayToFilter = arrayToFilter.filter(product => {
          const colors = get(product, 'colors', []);
          let found = false;
          for (let indexColor = 0; indexColor < colors.length; indexColor++) {
            const color = colors[indexColor];
            // Cannot call the method of the plugin since *this* is undefined.
            if (colorsSelected.indexOf(`${this.$colorService.getCodeFromId(product.productType, color.id)}`) > -1) {
              found = true;
              break;
            }
          }
          return found;
        });
    }
}

Really apreciate your help 馃槃

Try:

import Vue from 'vue'

// ...

Vue.prototype.$colorService

Yep, we tried this but it does not work.
EDIT: @clarkdo
the error we are getting when we try to execute Vue.prototype.$colorService is the following:

vue.runtime.esm.js:3143 Uncaught TypeError: Cannot read property '$options' of undefined
    at Object.get (index.js:118)
    at otherGetter (getters.js:21)
    at wrappedGetter (vuex.esm.js:734)
    at Vue.computed.(anonymous function) (http://localhost:3000/bershka/vendor.js:33676:42)
    at Watcher.get (vue.runtime.esm.js:3138)
    at Watcher.evaluate (vue.runtime.esm.js:3245)
    at Vue.computedGetter [as products/otherGetter] (vue.runtime.esm.js:3503)
    at Object.get [as products/otherGetter] (vuex.esm.js:536)
    at e (backend.js:1)
    at e (backend.js:1)

I don't know if it can help.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  路  3Comments

pehbehbeh picture pehbehbeh  路  3Comments

o-alexandrov picture o-alexandrov  路  3Comments

danieloprado picture danieloprado  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments