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
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.
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.
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
.
You could also just do this:
const initialData = {
someData: "Hello Vue!"
};
const app = new Vue({
el: '#vueApp',
data: {
myData: intialData
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With