Sending specific names as properties

Looking to streamline my repetitive form inputs by abstracting them into a component, I want the following functionality:

<InputElement title="someTitle" v-model="someName" @blur="someFunction" name="someName" type="someType">

The desired output would resemble the code snippet below

<template>
  <div>
    <label>Your name</label>
    <input v-model="username" @blur="validateNotEmpty" name="username" type="text">
    <p style="color:red" v-if="errors.applicantName === false">Fail</p>

    <label>Phone Number</label>
    <input v-model="phoneNumber" @blur="validateNotEmpty" v-mask="'###-###-####'" name="phoneNumber" />
    <p style="color:red" v-if="errors.phoneNumber === false">Fail</p>

    <label>Your email</label>
    <input v-model="email" @blur="validateEmail" name="email" type="email">
    <p style="color:red" v-if="errors.email === false">Fail</p>
  </div>
</template>

I've already created InputElement.vue

<template>
  <div>
    <label>{{ inputTitle }}</label>
    <input v-model="v-model" @blur="@blur" name="name" type="type">
    <p style="color:red">Fail</p>
  </div>
</template>

<script>
export default {
  props: ['inputTitle', 'v-model', '@blur', 'name', 'type']
}
</script>

Unfortunately, this approach falls short in multiple ways.

Any straightforward solutions in Vue.js for creating reusable form input components and passing reserved keywords as props?

Answer №1

If you need to pass v-model data from the parent component to the child component, you can achieve this by using value as a prop and emitting the input event following the guidelines in the VueJS documentation:

<template>
  <div>
    <label>{{ inputTitle }}</label>
    <input v-model="myvalue" @blur="onblur" :name="name" :type="type">
    <p style="color:red">Fail</p>
  </div>
</template>

<script>
export default {
  props: ['inputTitle', 'value', 'name', 'type'],
  computed : {
    myvalue : {
        set : function (newVal) {
            this.$emit('input',newVal);
        },
        get : function () {
            return this.value;
        }
    }
  },
  methods : {
    onblur : function (event) {
        this.$emit('blur',event);
    }
  }
}
</script>

You can then incorporate your custom component in the parent component like so:

<InputElement :input-title="someTitle" v-model="someName" @blur="someFunction" :name="someName" :type="someType">

Please note that I have not actually tested this code.

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

Javascript is coming back with a message of "Access-Control-Allow-Origin" not being allowed

I've been encountering some unusual challenges with my React application related to the Access-Control-Allow-Origin issue. Initially, I had similar issues with the login and registration system which I thought were resolved, but now I'm facing di ...

Duplicating labels with JavaScript

I need assistance with copying HTML to my clipboard. The issue I am encountering is that when I try to copy the button inside the tagHolder, it ends up copying <span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: ...

jquery dialog content vanishing upon second opening

My jQuery code is set up to display a dialog when a button is clicked. The issue I'm experiencing is that after closing the dialog and reopening it, the text area within the dialog appears empty with only three buttons visible. However, upon subsequen ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

Stop the annoying page flicker in Next.js 12 by implementing a custom dark mode using Tailwind CSS classes

Is there a way to prevent the page flash when implementing dark mode in Tailwind CSS using classes in Next.js v12 without relying on third-party packages like next-themes? I have explored different solutions: This StackOverflow Q&A How to fix dark mo ...

The Ajax form is failing to retrieve the expected PHP data

My login system uses a combination of ajax and php. The form validation is handled through javascript, with the form data then being sent to php for database checks. In the past, this method has worked well for me, but in this instance, it seems 'NOTH ...

Swap out flash for javascript

I am embarking on a new task: replacing the flash element with JavaScript on this page: (switching images for buttons for each image) Naturally, it must maintain the same appearance and functionality. I have come across some jQuery modules that achieve s ...

Trigger Knockout bindings once the ajax request has been completed

In the view, I have the following script: <script> MyObj.initModel(getUrl); $(document).ready(function () { ko.applyBindings(MyObj.viewModel, document.getElementById("someId")); ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Javascript tree structures that enable the drag-and-drop of multiple items

At the moment, our application utilizes the ExtJS tree view. We now have a need for users to be able to select multiple nodes (which the tree view already supports through a pluggable selection model) and then drag these selections to another section of th ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

What is the method for reverting style properties back to their CSS defaults using Javascript?

The php-generated page contains multiple elements structured like this: <td class="defaultTDStyle" style="color:userDefinedCustomColor" id="myTDId"></td> There is a default style in place with additional styles ap ...

Narrow down an array of objects by matching a specific property and value to a separate array of objects

I am facing a challenge with two sets of arrays - one for the headers (columns) of a table and the other for the rows. const headers = [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'n ...

Issue with jQuery AJAX error callback not triggering upon encountering an error

I'm currently facing an issue with implementing the management of an HTTP 413: Request entity too large error from my server. I've made the following attempt to address it: $.ajax({ url: "submit.php", data: { "data": POSTData ...

Using axios to retrieve data and then sending it to a localhost server using express

I'm a beginner in javascript and currently experimenting with fetching data from an API and posting it to my own server (localhost). For fetching the data, I am using axios as shown below: async function getNCAA() { axios .get(`https://api.th ...

Having an issue with Vue Dev Tools where the "Open in Editor" button is not functioning properly. Any suggestions on how to resolve this?

I followed a tutorial to implement a new feature, using the instructions found here: https://github.com/vuejs/vue-devtools/blob/master/docs/open-in-editor.md However, I encountered an error: "C:\Users\User\AppData\Local\Programs& ...

Javascript Encapsulation example

Could someone help me with this function query: var MyObject3 = function (a, b) { var obj = { myA : a, myB : b } ; obj.foo = function () { return obj.myA + obj.myB ; } ; obj.bar = function (c) { return obj.myA + c ; } ; return obj ; } ; I und ...