Establishing a default v-on event for a Vue component

Within my custom 'text-input' components, I include some default markup and an 'input' element.

An effective method for passing the value of the 'text-input' to its parent is by emitting an event when the value changes.

To handle and capture this emitted value, I currently use a v-on directive for each text-input component:

<text-input v-on:valueUpdated="storeInputValue" name='name'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='email'></text-input>
<text-input v-on:valueUpdated="storeInputValue" name='phone'></text-input>

However, I find this approach repetitive and am exploring the possibility of having the v-on listener directly within the component template itself:

<template v-on:valueUpdated="storeInputValue">
    ...
</template>

This way, a 'default' v-on listener would be set for the component every time it is used.

Answer №1

If you want to utilize v-model on custom components, it's totally possible.

HTML Example:

<div id="app>
    <text-input v-model="user.name" name="'name'"></text-input>
    <text-input v-model="user.email" name="'email'"></text-input>
    <text-input v-model="user.phone" name="'phone'"></text-input>
    <h4>{{user}}</h4>
</div> 

Script Implementation:

Vue.component('text-input', {
        name: 'text-input',
        template: `
        <div>
            <label>{{name}}</label>
            <input type="text" :value="value" @input="storeInputValue($event.target.value)" />
        </div>
        `,
        props: ['value', 'name'],
        methods: {
            storeInputValue(value){
                this.$emit('input', value);
            }
        }
    });
    
    //parent component
    new Vue({
        el: '#app',
        data: {
            user: {
                name: '',
                email: '',
                phone: ''
            }
        }
    }); 

You can check out the live example in this fiddle link.

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

What is the process for creating a unit test case for a button's onClick event with Jest?

In my attempt to unit test the onClick event of a button in a component, I encountered some challenges. Specifically, I am unsure how to properly test the onClick event when it triggers a function like Add(value). App.js function App(){ const[value,set ...

Struggling with NodeJs POST request issue

Let's imagine I have a specific URL https://exampleAPI.com/authorize?param1=value1&param2=value2 Where param1 and param2 are the payload values being sent. How can I execute a POST request in this particular way? I attempted the following: var ...

Is there a way to make Firebase Cloud Functions utilize ESLint?

Is there a specific command to activate ESLint for my cloud functions? Just to provide some context, I executed firebase init and completed the setup process, but it ended up using ESLint instead of TSLint which was unexpected. After that, I ran firebase ...

Accessing JSON data model from Ember route or controller

Exploring the capabilities of Ember.js Is it possible to expose my data model as JSON through a route or controller? The object saved in the store looks like this: this.store.createRecord('Person', { id: 1, name: this.get('name'), ...

What are the steps for integrating Landbot into a Next.js application?

I've been attempting to integrate Landbot into my Next.js application, but I'm facing some difficulties. I tried to modify the _document.js file and insert the necessary code into the body section, however, it doesn't seem to have any impact ...

What is the best way to break down my node module into separate files?

I am currently in the process of organizing my node module functions by splitting them into separate files to accommodate numerous functions that need to be added. My objective is to call the main file's functions from files located within the lib di ...

What is a more streamlined approach to creating a series of methods and functions that alter a single variable consecutively?

My JavaScript project involves handling sub-arrays within a long data file that cannot be altered. The data, stored in a variable named data, is retrieved via a script tag with a specified URL property. I need to extract and modify specific sub-arrays from ...

One method for routing pages in React Router is to have a shared component that is displayed on multiple pages, as well as a

My app.js consists of multiple pages with the navbar and sidebar as components, but my login page is different and does not include these elements. How can I use react-router to create separate routes for the login page without the sidebar and navbar, whil ...

You must use the 'new' keyword in order to invoke the class constructor

Although similar questions have been asked before, my situation differs from the typical scenarios. I have a basic base class named CObject structured as follows: export class CObject extends BaseObject { constructor() { super(); } sta ...

Is it possible for a Vue Boolean prop to be true if present and false if absent?

Within my Vue component, I've implemented a Boolean prop named "obj" with the following definition: obj: { Type:Boolean, default: false} To set it to true, one can simply do as follows: <my-component :obj="true"></my-component> Yet, I ...

Managing array elements in React: removing and duplicating items

One of my tasks is to incorporate a copy and delete button within a table. My goal is to pass the index from the map to the delete and copy onclick functions, however, I am encountering an issue where copying a row results in it having the same index as th ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this: <div ng-repeat="comment in comments"> <li class="item" ng-class-even="'even'"> <div class="row"> ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Using React in ES5 to create a button that triggers two separate functions with a

I have encountered an issue with two React classes that both contain a render function returning forms with buttons. In class A, I had to import class B in order to use the form from class B. The problem: Whenever I click the inner button, the outer butto ...

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

Leverage axios over fetch calls within Workbox

As I work on caching content for my project using Workbox, I've successfully saved all my js and css files, fonts, etc. However, I'm facing an issue with caching my project's content stored in my PC. When using axios to fetch data from my da ...

The nodemailer module in Node.js encountered an issue while trying to send an email, resulting

Looking to confirm registration, I want to send an email from my server (kimsufi). To accomplish this, I am utilizing nodemailer which can be found at https://github.com/andris9/Nodemailer Encountering the following error: Error occurred Sendmail exited ...

Tips for deactivating dates in the jquery datepicker that correspond to entries in a MySQL database

Is there a way to disable dates directly from a MySQL database in jQuery Datepicker? It seems tedious to constantly update dates in JavaScript, so I'm exploring the option of storing future disable dates in the MySQL database and displaying them in th ...