访问 Vue 实例的 Vue 指令? [英] Vue directive to access the Vue instance?

查看:29
本文介绍了访问 Vue 实例的 Vue 指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从指令访问 Vue 实例?

我有这个 HTML

还有这个脚本

var app = new Vue({el: '#vueApp',数据: {我的数据:空}});Vue.directive('init', function(el, binding) {app.myData = binding.value;});

它抛出这个错误:

<块引用>

无法解析指令:init

解决方案

您的特定错误是因为指令是在 Vue 之后创建的.

对于这个特定的指令,你可以通过 vnode.context 访问 Vue.

Vue.directive('init', {绑定(el,绑定,vnode){vnode.context.myData = binding.expression;}});const app = new Vue({el: '#vueApp',数据: {我的数据:空}});

示例.

您也可以考虑使用 vnode.context.$root.

发表评论编辑

你也可以这样做:

const initialData = {someData:你好,Vue!"};const app = new Vue({el: '#vueApp',数据: {我的数据:初始数据}});

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

这篇关于访问 Vue 实例的 Vue 指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆