vue 3 custom global directive for detecting clicks outside

My goal is to change the row value to 10 when clicking on <textarea>, and revert it back to 6 if clicked outside of the element. I am new to Vue.js 3 and struggling with this issue, particularly regarding directives.

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

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

Answer №1

Give this code a whirl:

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c2b4b7a782f1ecf0ecf0fb">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="demo">
  <textarea @click="setRow" :rows="row" v-click-out="removeRow"></textarea>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Drawing unusual shapes using canvas arcs in Coffeescript

@.ctx.lineWidth = 20 @.ctx.moveTo(i.x, i.y) @.ctx.arc(i.x, i.y, 3, 0, Math.PI * 2) Can you explain how the code snippet above contributes to the image displayed? ...

What is the process for displaying a Bootstrap Icon on a webpage?

I recently started using Bootstrap and I'm in the process of creating a login screen for my app. I want to incorporate MDBIcons for Google, Twitter, and Facebook. I referred to the documentation provided at However, upon previewing my webpage, I enco ...

Tips for verifying the background color on a webpage with Robot Framework

Seeking assistance on validating the background color in a webpage using robot framwork. Can someone provide guidance or tips? ...

Exploring the process of defining directives with Vue 3's composition API

How can directives be defined and used in Vue3's composition API using the new syntactic sugar in SFC <script setup> format? In the past, with the options API, it looked something like this: import click_outside from "@/directives/click-out ...

Starting a new React project

prtScn I'm encountering an issue while trying to initiate a new react app in Visual Studio Code. I have been following the given instructions as follows: in the visual code terminal : create-react-app sali (sali is the name) npm install node node_m ...

Embedding the local host into a href link in NextJS

After creating a menu with the Link component in NextJs using href=#contact, I encountered an issue. When I use querySelector on this a element, the href unexpectedly changes to http://localhost:3000/#contact', preventing me from scrolling to that sec ...

The resource-intensive nature of ExpressJs HTTP Streaming is causing my disk space to deplete rapidly

My express server app.get('/data', (_, res) => { const interval = setInterval( () => res.write(`${Math.random().toString()}\n`), 1000 ); res.on('close', () => { clearInterval(interval); ...

Tips for capturing a screenshot of the ESRI Map using Angular

Is there a way to capture a screenshot of the Esri map in its current state on the UI and then convert it into a PDF for download using Angular? Below is my current .ts code, but I am open to any additional suggestions. esri-map.component.html <!-- Map ...

Information displays instantly in the initial milliseconds

When developing dynamic web pages with Nuxt, I encountered an issue in the pages directory where a file named _url.vue is located. The contents of this file are as follows: <template lang="pug"> div component( v-for= ...

Tips for importing an external Vue script into your Vue.js application

Being new to Vue.js, I have a question. I have written a Vue script (Methods) that I would like to use in other components of my App. I have placed this code within a component between two script tags, but I am unsure of how to utilize the functions from t ...

Changing the anchor tags within a string and returning the modified string using a JavaScript function

When retrieving string data from a CMS, I noticed it contains anchor links that need to be modified. For my app built using the Ionic Framework, I want to add an onClick function to these "a" tags to utilize the "inappbrowser" Cordova plugin. To do this, ...

Syntax error occurs while attempting to render the return statement in a React Component

Just starting out with React and encountering a syntax issue that has me stumped. I'm working on a React Component and I thought I had the opening/closing { & }'s correct, but clearly there's something missing based on the error message it&a ...

What is the process for converting a regular text input to a password input in Laravel?

Looking to update the text input in my Laravel project to a password input with asterisks for security. <div class="col-md-3"> <div class="form-group"> {{ Form::label('user-password','Password') ...

Error encountered with AJAX call when attempting to utilize string method

I am looking to add HTML content to a TinyMCE editor in an ASP.NET MVC project. After some thought, I have found a solution that involves converting the HTML file to a string on the server side and then calling it using Ajax on the client side. Here is a ...

What is the proper way to initialize MongoDB and Express?

I have a unique app that utilizes express and interacts with mongodb. Here is how I typically kickstart my app: 1. Launch Mongodb mongod --dbpath data --config mongo.conf" 2. Initiate Express node server.js My pondering is, can these processes be comb ...

The error message "Exceeded the maximum call stack size in Javascript"

My current project involves using socket.io for sending and receiving data from a server. I have implemented a "Create Game" button on the client side that triggers the creation of a new GameServer on the server side. Following that, I am displaying the ga ...

What is the best method for assigning a default value to the file input tag in HTML?

Can anyone help me with this code snippet? <input name="GG" type="file" value="< ?php echo $data['image'] ?>"> I was trying to set a default value in the form edit, but it seems to not be working. Does anyone know how to set a defau ...

Utilizing the child's property of an object in Three.js beyond the loader.load function

I am looking for a way to dynamically update the color property of an object using dat.GUI(). It is straightforward when working with objects created using three.js geometry. However, I am facing some challenges as I am working with imported objects (.obj ...

Having trouble monitoring the default close button on a desktop window

Currently working on a windows desktop app that utilizes node.js and backbone.js. I'm looking to trigger a specific action when the user closes the application either by clicking the close button on the title bar or right-clicking on the app in the Wi ...

What is the best way to implement function chaining in TypeScript?

I'm interested in implementing function chaining in typescript. Let's consider a sample class: export class NumberOperator { private num; constructor(initialNum) { this.num = initialNum; } public add(inc = 1) { this.num += inc ...