Yerko Palma
Yerko Palma

Reputation: 12339

How to extend Vue.prototype reactively

I'm trying to write a simple plugin. It's a directive to add ripple effect to any element. So far the custom directive works fine (check here), but I want to add some data to the Vue instance so the user can modify some values globally. I wan it to be used like this.

new Vue({
  ripple: {
    color: '#f18c16'
  }
})

and that would modify the color of all ripple directives in this instance. As far as I know this isn't documented, so I inspect a litle in some Vue plugin and I came to this code.

const ripple = {
    color: '#000'
}
const init = Vue.prototype._init

Vue.prototype._init = function(options) {
    options = options || {}
    Vue.util.defineReactive(this, '$ripple', ripple)
  init.call(this, options)
}

And in my directive I use it like this

  if (this.modifiers.white) {
    point.style['background-color'] = '#fff'
  } else {
    point.style['background-color'] = this.vm.$ripple.color
  }

But that only adds the $ripple property to my Vue instance and the declaration that I expected isn't working. Check here. So, my question is how can I use the ripple option defined for my directive? Is there any official/standard way to do this?

Upvotes: 2

Views: 1440

Answers (1)

pespantelis
pespantelis

Reputation: 15372

You do not need to define reactivity.

Simply use this:

this.vm.$options.ripple.color

instead of this:

this.vm.$ripple.color

https://jsfiddle.net/pespantelis/tzw9ho3k/6/

Upvotes: 1

Related Questions