Vue directive to access the Vue instance?

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

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

回答1:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!