1

I accidentally found this documentation of Vue v1, which had a feature to watch attributes on the element that the directive is bound to :

<div v-example v-bind:a="someValue"></div>

Vue.directive('example', {
  params: ['a'],
  paramWatchers: {
    a: function (val, oldVal) {
      console.log('a changed!')
    }
  }
})

I am building a custom directive library using Vue 2.7. and I was looking for a similar feature, but it's now missing in the latest documentation.

Anyway I have implemented a different logic using update hook where I need to programmatically extract attributes from the element.

const myDirective: DirectiveOptions = {
  update (el: any, binding: any) {
    const customAttribute = el.getAttribute('customAttribute')
    doSomething(customAttribute)
  }
}

But it's not perfectly match with the requirement as the update hook is triggering unnecessarily with other elements under the same parent. So this function executes multiple times unnecessarily and also I need to do some hacks to keep state of the directive.

My question is: Is this feature still available somewhere else now? or did Vue introduce a different feature to achieve the same requirement?

Please note that my project is just a set of Directives only, so it doesn't have access to components or root level to place a regular watchers to check for state changes.

2
  • 1
    If you're using Vue 2.7, you're looking for these docs. The latest docs you linked are for Vue 3 instead. Commented Dec 5, 2023 at 19:58
  • 1
    You should also be able to skip unnecessary work on duplicate calls by comparing the third and fourth arguments of the directive, vnode and oldVnode respectively. Commented Dec 5, 2023 at 20:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.