Vue - Encapsulate HTML5 tag

I am looking to develop a component that encompasses a textarea element. The goal is to incorporate customized functionality and styling without isolating it in its own scope - instead, I want the parent to be able to bind to regular events like input.

An example of what I need, but currently does not work (issue highlighted in parent.vue):

area.vue:

<template>
    <textarea rows="1"></textarea>
</template>

<script>
    export default {
        mounted() {
            // do something...
        }
    }
</script>

<style scoped>
    textarea {
        height: 100%;
    }
</style>

parent.vue:

<template>
    <area @input="doSomething"></area>
</template>

<script>
    import Area from "./area.vue"

    export default {
        methods: {
            doSomething(){
                // NOT TRIGGERED!
                // `input` event is not passed over to parent scope
            }
        },
        components: {
            Area
        }
    }
</script>

I prefer not to manually insert this.$emit calls in the component.

Answer №1

To make it work, just insert .native after @input.

When Vue's v-on/@ is used on a component (without .native), it will only respond to custom events specified by emit.

Answer №2

Passing methods from a parent component to a child component as props is a common practice in Vue.js development.

Parent Component Example:

<my-child :custom-method="handleCustomEvent"></my-child>

Child Component Example:

# Template
<button @click="customMethod">Click me</button>

# Script
export default {
  props: ['customMethod'],
  ...

Answer №3

Regrettably, this action is not possible as it stands. However, there is a workaround that can help achieve a similar result.

mounted() {
    var self = this;
    Object.keys(Event.prototype).forEach(function(ev) {
       self.$refs.text.addEventListener(ev.toLowerCase(), function(d) {
           self.$emit(ev.toLowerCase(), d);
           console.log("emitting", ev, d);
       })
   })
}

By implementing this code snippet, you are able to obtain mousedown, mouseup, mouseover, mouseout, mousemove, mousedrag, click, dblclick, keydown, keyup, keypress, dragdrop, focus, blur, select, and change events. Subsequently, in your parent template...

<my-textarea @keyup="update()" @change="somethingElse()"></my-textarea>

For reference, here's the fiddle link: https://jsfiddle.net/rdjjpc7a/371/

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

Leveraging Extract-Text-Webpack-Plugin within Vue CLI 3

I have successfully developed an application using the Vue CLI, which now hides Webpack configuration behind vue.config.js. My current goal is to extract my CSS into a styles.css file. However, at the moment, it is extracting to randomly named files with s ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

What could be the reason for the malfunction of my for loop within my JSON operation?

Hi everyone, I'm new to coding and currently working on a project involving Twitch Viewer on FreeCodeCamp. I've managed to extract information from the JSON file and display it in my HTML code. However, I'm encountering an issue where I am ...

Toggling classes with Vue.js within a v-for loop

Currently, I am in the process of creating a list of items using a v-for loop. The data I am using comes from an API provided by the server. items: [ { foo: 'something', number: 1 }, { foo: 'anything', ...

Error message: The line chart in angular-chartjs is encountering an issue with the function t.merge not

I am currently working on implementing a line chart example from the following source: . However, I am encountering an error and would appreciate any guidance or pointers to resolve it. Here is the error displayed in the console. Below is the code snippe ...

How can we utilize data retrieved from Mongodb in Express and pass it to a Jade view using the res.render function?

Within my node/express application, I need to pass data retrieved from mongoose to my jade view. The code below in routes.js accomplishes this task: app.get('/newrequest', function (req, res) { Account.find({}, function (err, data) { ...

Unexpected dates are being displayed when printing an array of dates using Moment.js

I've run into an issue with moment js in my code snippet. Specifically, weekStart is supposed to be the start of the week (19th Jul) and weekEnd should be the end of the week (25th Jul). When printing them individually, both dates show up correctly. ...

Struggling with my `welcome.blade.php` not detecting Vue imported within my Nuxt.js directory

I have been working with Nuxt.js on my Laravel project. Combining them was a necessary step since they each come with their own boilerplate during installation into the project. I managed to make almost everything work smoothly until I encountered an issu ...

Problem with Chrome's version causing regex malfunction

Seeking assistance with extracting a string from a URL of an image using regular expressions and the match() function in JavaScript. The code works flawlessly on Chrome version 62, but encounters issues on older versions like Chrome 58. Here are the specif ...

Create an input box with a designated class

When I click the button in my HTML and JavaScript code below, I am able to dynamically add a text field and radio button. This functionality is working properly. However, I also want the newly generated text field to have the same font size and appearance ...

Module 'prompt-sync' not found

When attempting to take user input in Node.js using the prompt module, I encountered the following error message: node:internal/modules/cjs/loader:998 throw err; ^ Error: Cannot find module 'prompt-sync' Require stack: - D:\Code\C+ ...

Verify the occurrence of a search result and if it appears more than once, only show it once using JavaScript

Hello all. Currently, I am developing an online users script using NodeJS and SocketIO. The functionality works fine, however, I am encountering an issue where if a user connects from multiple browsers, windows, or devices, it displays duplicate results li ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

What is the best way to use Rails active storage and VueJS to directly upload files to S3?

I've encountered a challenge in uploading a file to s3 using direct upload s3. My current setup is Rails 5.2 with active storage. However, the Active Storage guide only provides instructions for uploads using built-in rails views. I'm now seeking ...

Tips on utilizing JavaScript to retrieve all HTML elements that have text within them, then eliminating the designated element and its descendants

Simply put, I am looking to extract all the text-containing elements from the HTML and exclude specific elements like 'pre' or 'script' tags along with their children. I came across information suggesting that querySelectorAll is n ...

Learn how to incorporate a consistent header and footer across multiple pages on a website with Node.js, ExpressJS, and either hbs or ejs templates

Creating a common header (navbar) and footer page to be included in multiple/several pages of a website. I want to create a dynamic website using Node.js and Express.js. The code for the navbar and footer will be placed in a common file named header.html ...

Imagine you are looking to execute an if/else statement

I'm having some trouble with this code that is meant to print different values based on certain conditions, but it only seems to be printing one value consistently. See the code snippet below: let twitterfollowers; let websitetraffic; let monthlyre ...

Enhance link with dynamic content using an AJAX call

I need help appending a picture after a link with the same URL as the link. The current AJAX code is producing the following result: <a href="images/Draadloos.png" data-lightbox="gallerij"></a> Here is an example of what I would like to achie ...

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...