Vue to access a Vue instance?

How do you access a Vue instance from a directive?

I have this HTML

<div id='vueApp' v-init='my initial data from server-side'>

      

and this script

var app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});

Vue.directive('init', function(el, binding) {
    app.myData = binding.value;
});

      

It throws this error:

Failed to execute directive: init

+3


source to share


1 answer


Your specific error has to do with the directive being created after Vue.

For this particular directive, you can access Vue via vnode.context

.

Vue.directive('init', {
  bind(el, binding, vnode){
    vnode.context.myData = binding.expression;
  }
});

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});

      

An example .



You can also use vnode.context.$root

.

Edit

You can also just do this:

const initialData = {
    someData: "Hello Vue!"
};

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: intialData
    }
});

      

+9


source







All Articles