Gorilka
Gorilka

Reputation: 504

How to insert a function into a directive Vue 3?

I need to write a specific global directive that should perform the same function in different hooks. How can I implement something like this

export default {
  directives: {
    widthAsChild: {
      widthAsChild(el) {
        el.style.width = getComputedStyle(el.firstChild).getPropertyValue(
          "width"
        );
      },

      mounted(el) {
        widthAsChild(el);
        window.addEventListener("resize", () => {
          widthAsChild(el);
        });
      },
    },
  },
}

Upvotes: 0

Views: 181

Answers (1)

tony19
tony19

Reputation: 138246

The function has to be declared outside the directive's declaration object. One way to do that is to use an IIFE that contains a local method that you can can reuse in the returned directive declaration:

export default {
  directives: {
    widthAsChild: (() => {
      const widthAsChild = el => {
        el.style.width = getComputedStyle(el.firstChild).getPropertyValue("width");
      }
      return {
        mounted(el) {
          widthAsChild(el);
          window.addEventListener("resize", () => {
            widthAsChild(el);
          });
        },
      }
    })()
  }
}

demo 1

Alternatively, you could move that to a separate file:

// @/directives/widthAsChild.js
const widthAsChild = el => {
  el.style.width = getComputedStyle(el.firstChild).getPropertyValue('width')
}

export default {
  mounted(el) {
    widthAsChild(el)
    window.addEventListener('resize', () => {
      widthAsChild(el)
    })
  }
}

// MyComponent.vue
import widthAsChild from '@/directives/widthAsChild'

export default {
  directives: {
    widthAsChild,
  }
}

demo 2

Upvotes: 1

Related Questions