【问题标题】:Vuejs 2.0: How to access vm instance within hook functions in custom directives?Vuejs 2.0:如何在自定义指令的钩子函数中访问 vm 实例?
【发布时间】:2017-08-04 07:25:45
【问题描述】:

在 Vuejs 1.0 中,它能够从 this.vm 访问 vue 实例,但我在 vue 2.0 中找不到这样做的方法。

我实际上是在尝试编写一个自定义指令来更新绑定数据,当一个元素被一个不会触发v-model 中的任何更新的 jquery 插件更改时。

`<input id="dayparting_switch" 
  v-model="options.dayparting" 
  v-observe="options.dayparting" 
  :cheked="options.dayparting" 
data-off="Disabled" data-on="Enabled" data-toggle="toggle" type="checkbox">`
Vue.directive('observe', {
    bind(el, args) {
        var vm = this.vm;
        $(el).change(function() {
            vm.$data = 'changed';
        });
    }
});

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    我看到你想访问你的指令在其中呈现的组件。

    Vue.directive('observe', {
      // in the bind function, the 3rd argument is vnode (the VDOM) created by Vue.
      bind(el, bindings, vnode) {
       // vnode.context is the scope where the directive is rendered.
       const vm = vnode.context 
       $(el).change(function() {
         vm.$data = 'changed';
       });
      }
    });
    

    查看源代码VNode context中的这一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-28
      • 2017-12-26
      • 1970-01-01
      • 2015-09-20
      • 2016-04-04
      • 1970-01-01
      • 2015-04-03
      • 2021-12-12
      相关资源
      最近更新 更多