Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 842
KeironLowe Avatar asked Jan 11 '17 11:01

KeironLowe


People also ask

Is Vue 2 way data binding?

Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. The v-model directive makes two-way binding between a form input and app state very easy to implement.

How do I transfer data from components to Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!

How does one assign directive in Vue?

Using the v-if , v-else , and v-else-if Directives. Vue. js comes pre-packaged with a number of directives that developers commonly use when working within the framework. Directives such as v-if , v-show , v-on , v-model , v-bind , v-html , and more are all provided for you out-of-the-box.

What is $V in VueJS?

$v is an object that calls vuelidate (at the time of writing the comment, supported in version Vue. js 2.0), which is intended to check every input, which is made in a non-html form.


1 Answers

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/

like image 129
craig_h Avatar answered Sep 23 '22 02:09

craig_h