Vue.js 2, change data from directive
Asked Answered
S

1

9

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.

Substantial answered 11/1, 2017 at 11:48 Comment(0)
P
21

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/

Pervious answered 11/1, 2017 at 12:5 Comment(2)
The docs say to treat everything but 'el' as read only. vuejs.org/v2/guide/custom-directive.html Is there another way to do this?Iberia
Hmm. I would argue that this isn't a modification in the sense that the docs are referring to, it's just a reference to the Vue instance, exactly the same as referencing a vue instance from outside the instance itself.Pervious

© 2022 - 2024 — McMap. All rights reserved.