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
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 } });