Jamie Marshall
Jamie Marshall

Reputation: 2304

get 'this' in nuxt plugin?

So you can create a plugin in nuxt like this:

const utils = {
  name: utils,
  emmitModel(name, val) {
    const value = Object.assign({}, this.value)
    value[name] = val
    this.$emit('input', value)
  },
}

export default ({ app }, inject) => {
  inject('utils', utils)
}

However, in the above, 'this' is not defined. How do I access the 'this' component context inside emmitModel?

Upvotes: 0

Views: 749

Answers (1)

Jeremy Abraham
Jeremy Abraham

Reputation: 56

Assuming this references your Vue instance, wrap your utils object in a Vue instance, like so:

const utils = new Vue({
  // ..stuff here
})

export default ({ app }, inject) => {
  inject('utils', utils)
}

And then within the Vue object you can fully use component methods, computed, data, and access the VM and utils will be injected in nuxt as this.$utils

Upvotes: 3

Related Questions