首页 > 解决方案 > VueJS - 如何从指令访问 mixin 方法

问题描述

简单代码:

Vue.mixin(
    {
        methods :
        {
            test ()
            {
                return 'test';
            }
        },
    }
);

Vue.directive('my-directive',
    {
        inserted (el)
        {
            this.test();
        }
    }
);

[Vue 警告]:指令 my-directive 插入钩子中的错误:“TypeError:无法读取未定义的属性 'test'”

标签: javascriptvue.jsvuejs2

解决方案


Vue.mixin(
    {
        methods :
        {
            test ()
            {
                return 'test';
            }
        },
    }
);

Vue.directive('my-directive',
    {
        inserted (el)
        {
            //
        },
        bind(el, binding, vnode)
        {
            vnode.context.test();
        }
    }
);

推荐阅读