Ask Your Question
4

How can a custom directive for detecting clicks outside of an element be transferred from Vue 2 to Vue 3?

asked 2022-10-18 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-26 22:00:00 +0000

qstack gravatar image

The process of transferring a custom directive from Vue 2 to Vue 3 is largely the same, but there are a few differences in the implementation due to changes in the Vue 3 API. Here is an example of how to transfer a directive that detects clicks outside of an element from Vue 2 to Vue 3:

Vue 2 Implementation:

Vue.directive('click-outside', {
  bind: function(el, binding) {
    el.clickOutsideEvent = function(event) {
      if (!(el == event.target || el.contains(event.target))) {
        binding.value(event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unbind: function(el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  }
});

Vue 3 Implementation:

const clickOutside = {
  beforeMount: function(el, binding) {
    el.clickOutsideEvent = function(event) {
      if (!(el == event.target || el.contains(event.target))) {
        binding.value(event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unmounted: function(el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  }
};

const app = createApp(...);
app.directive('click-outside', clickOutside);

As you can see, the main differences between the two implementations are:

  • bind and unbind have been replaced with beforeMount and unmounted.
  • The directive is now defined as a separate object, rather than being registered directly on the Vue instance.
  • The createApp function is used to create the Vue instance, rather than the new Vue syntax.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-18 11:00:00 +0000

Seen: 11 times

Last updated: May 26 '21