KeironLowe
KeironLowe

Reputation: 731

Vue.js 2, change data from directive

Using single file components, how can I change a data property from a directive?

So for example, I've got...

export default {
    name: 'app',
    data: function() {
        return {
            is_loading: true
        }
    },
    directives: {
        do_something: {
            bind: function(el, binding, vnode) {
                // Change the is_loading property
            }
        }
    }
}

At first I thought I could do this.is_loading = false but this is undefined.

Upvotes: 9

Views: 9124

Answers (1)

craig_h
craig_h

Reputation: 32694

To refer to this in a directive you can simply use vnode.context, so in you directive you would have:

    do_something: {
        bind: function(el, binding, vnode) {
            // same as this.is_loading in a directive
            vnode.context.is_loading = false;
        }
    }

Then in your markup you would do:

<div v-do_domething></div>

Here's the JSFiddle: https://jsfiddle.net/3qvtdgyd/

Upvotes: 21

Related Questions