简体   繁体   中英

How to scope a property to a custom directive in Vue.js?

is there a way to scope a property to a directive? Something like this so I can add foundation to it and clear it up (removing event listeners etc.) when the element is unbound?

Vue.directive('toggler', {
  inserted(el) {
    this.toggler = new Foundation.Toggler($(el)); 
  },
  unbind() {
    this.toggler.destroy();
  },
});

ok so this achieves what I wanted. Assigning the property to the element does the job.

Vue.directive('f-toggler', {
  inserted(el) {
    /* eslint-disable no-param-reassign */
    el.fToggler = new Foundation.Toggler($(el));
  },
  unbind(el) {
    el.fToggler.destroy();
  },
});

You need to use vnode.context which will give you access to the data properties on the Vue instance:

Vue.directive('toggler', {
  inserted(el, binding, vnode) {
    vnode.context.toggler = new Foundation.Toggler($(el)); 
  },
  unbind(el, binding, vnode) {
   vnode.context.toggler.destroy();
  },
});

Here's a JSFiddle to show the basic process: https://jsfiddle.net/dv5n39ta/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM