Liza
Liza

Reputation: 129

vue 3 global directive click-outside

what i want is when i click on <textarea> i want row value to be 10, If you click outside the <textarea> I want line 6 how can i do this i am newbie in vue js 3. I couldn't figure out how to do this. I couldn't figure out how to do about directives.

<template>
    <div>
        <textarea :rows="row"></textarea>
    </div>
</template>

<script>
export default {
    data() {
        return {
            row: 6
        }
    }
}
</script>

Upvotes: 4

Views: 4468

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

Try like following snippet:

const clickOutside = {
  beforeMount: (el, binding) => {
    el.clickOutsideEvent = event => {
      if (!(el == event.target || el.contains(event.target))) {
        binding.value();
      }
    };
    document.addEventListener("click", el.clickOutsideEvent);
  },
  unmounted: el => {
    document.removeEventListener("click", el.clickOutsideEvent);
  },
};
const app = Vue.createApp({
  data() {
    return {
      row: 6,
    };
  },
  methods: {
    setRow() {
      this.row = 10
    },
    removeRow() {
      this.row = 6
    }
  }
})
app.directive("clickOut", clickOutside).mount('#demo')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>
<div id="demo">
  <textarea @click="setRow" :rows="row" v-click-out="removeRow"></textarea>
</div>

Upvotes: 5

Related Questions