David Alsh
David Alsh

Reputation: 7675

How do I know if a component includes a binding on a directive

I have a directive called my-custom-directive This is how i'm using it

<my-component
    v-model="things.value"
    v-bind:error="things.error"
    v-my-custom-directive>
</my-component>

inside my-custom-directive, how do I know if my-component has the attribute v-bind:error?

Upvotes: 0

Views: 83

Answers (1)

Jacob Goh
Jacob Goh

Reputation: 20845

By using Vnode

vnode.data.attrs for DOM element (e.g. https://codepen.io/jacobgoh101/pen/RMRBbw?editors=1111)

vnode.componentOptions.propsData for Vue Component (e.g. https://codepen.io/jacobgoh101/pen/wmWxqd?editors=1011)

Vue.directive("focus", {
  // When the bound element is inserted into the DOM...
  inserted: function(el, binding, vnode) {
    if (
      vnode.data &&
      typeof vnode.data.attrs !== "undefined" &&
      vnode.data.attrs.hasOwnProperty("error")
    ) {
      // is DOM
    } else if (
      vnode.componentOptions &&
      typeof vnode.componentOptions.propsData !== "undefined" &&
      vnode.componentOptions.propsData.hasOwnProperty("error")
    ) {
        // is Vue Component
    }
  }
});

Upvotes: 1

Related Questions