Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue directive to access the Vue instance?

Tags:

vue.js

How do you access the 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 resolve directive: init

like image 730
Aximili Avatar asked Mar 28 '17 22:03

Aximili


People also ask

What is a Vue instance?

A Vue instance is essentially a ViewModel as defined in the MVVM pattern, hence the variable name vm you will see throughout the docs. When you instantiate a Vue instance, you need to pass in an options object which can contain options for data, template, element to mount on, methods, lifecycle callbacks and more.

What is V-bind used for?

The v-bind directive is a Vuejs directive used to bind one or more attributes, or a component prop to an element. If that attribute is binded to our data defined in Vuejs instance then dynamically changes can be observed as data changes.


1 Answers

Your particular error is because the directive is created after the Vue.

For this particular directive, you could access the Vue through vnode.context.

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

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

Example.

You might also consider using vnode.context.$root.

Post Comment Edit

You could also just do this:

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

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: intialData
    }
});
like image 68
Bert Avatar answered Sep 22 '22 09:09

Bert