Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example:

.input-group.input-group-sm
     .input-group-addon Purchase Price
      input.form-control(v-model='purchase_price')

  .input-group.input-group-sm
    .input-group-addon Net Rental Income
    input.form-control(v-model='rental_income_net')

All of these input fields have data properties that are altered using v-model within the component.

I am looking for a way to achieve the same formatting and output while simplifying the process by extracting the bootstrap field boilerplate. Ideally, I would like to be able to write something like this:

cell(title='Purchase Price' v-model='purchase_price') 
cell(title='Net Rental Income' v-model='rental_income_net') 

However, the above approach does not work as input fields do not seem to accept slots. Additionally, I want to avoid writing extensive event listeners and instead have clean code similar to the example provided. Is this possible?

Answer №1

I have limited knowledge of pug, so I have provided a vanilla HTML version. Below is an example of a cell component that can be converted into a single file component.

Vue.component("cell", {
  props:["value", "title"],
  template: `
    <div class="input-group input-group-sm">
      <div class="input-group-addon">{{title}}</div>
      <input class="form-control" v-model="internalValue">
    </div>
  `,
  computed:{
    internalValue:{
      get() {return this.value},
      set(v) {this.$emit("input", v)}
    }
  }
})

Answer №2

Hey Bert, your solution is fantastic! I also discovered Simon Herteby's helpful answer on the Vue forum, presenting a Single File Component approach:

<template lang='pug'>
  .input-group.input-group-sm
    .input-group-addon {{ title }}
    input.form-control(v-model='interface')
</template>


<script>
  export default {
    props: ['title', 'value'],
    name: 'Cell',
    computed: {
      interface: {
        get(){
          return this.value
        },
        set(val){
          this.$emit('input', val)
        }
      }
    }
  }
</script>

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

Sending an array from the server to the client using Node and Express during page loading?

I am utilizing Node and Express in my project. The application fetches data from a remote database on page load and sends it to a handlebars template server-side. However, I would like this JSON data to also be accessible for client-side interactions. How ...

Node.js now supports ES6 imports using the `--experimental-modules` flag,

Experimenting with ES6 imports in node using the -experimental-modules flag. Here are the steps: mkdir testfolder cd testfolder npm init npm i --save testing-library touch script.mjs Next, add the following code to script.mjs: import { test1, test2, tes ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

Sharing data from AJAX calls in Vue using vue-resource

After using Vue resource, I'm attempting to create an AJAX call that is based on the data received from a prior AJAX call. I have successfully bound the data fetched from /me to the userDetails prop. However, when trying to pass userDetails.id into t ...

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

Dealing with nested try/catch mechanism in NodeJS

As a Node.js novice, I am delving into the realm of coding two nested try/catch blocks with retry logic. My goal is to have the inner try/catch block send any caught errors to the outer catch block, where I will increment a retry count by 1. Once this co ...

What could be causing my React Router to fail in displaying the content of Home.js?

My <Route> is not functioning as expected The Route leading to the homepage does not show the content from the Home.js file import "./App.css"; import Navbar from "./components/Navbar"; import { BrowserRouter as Router, Route, Ro ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Tips for resolving a blank screen issue when attempting to render components using the `:is="component"` attribute

Working with NativeScript-Vue for Android, my goal is to display a component based on button taps. To achieve this, I am utilizing this plugin which helps in integrating a global SideDrawer for smooth navigation. The buttons within the SideDrawer are used ...

The form submission has been cancelled as the form connection is not active - Utilizing VueJs within laravel 8

I am trying to troubleshoot a response issue using the Google inspect tool. Despite checking Network>>XHR, I can't find any response. However, in the console, I saw the message "Form submission canceled because the form is not connected". The sc ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

center text above images in flexbox when page is resized

When resizing the page, I'm facing an issue where the links overlap with the images in a flexbox layout. It seems like the padding and margin between the images and links are not working due to them not being "related" or connected. I believe I need t ...

What exactly is the purpose of utilizing node js and can someone explain to me what constitutes a

After mastering HTML and CSS, I've started diving into JavaScript. However, I'm curious about Node.js. What exactly is it, why do I need it, and can you explain what a framework is in general? Sorry if these questions sound silly! ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

Issue with AngularJS ui-router failing to resolve a service call

I am facing an issue while trying to implement the resolve feature in my ui-router state provider. Here is how I have configured it: app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stat ...

What is the reason behind Visual Studio intellisense not displaying the methods of XMLHttpRequest objects?

Why am I unable to access the open and send methods of the XMLHttpRequest object in Visual Studio's Intellisense? var httprequest = new XMLHttpRequest(); httprequest. I cannot see the methods in Intellisense after the dot. ...

Upon the creation of a new Post and attempting to make edits, the field is found to be blank

<template> <div class="card m-3"> <div class="card-body"> <Form method="post" @submit="submitData" :validation-schema="schema" ref="myForm" v-slot="{ errors, ...

Checking the status of a checkbox after submitting using AngularJs

For my first application, I am utilizing AngularJs and JavaScript to display information from an API as checkboxes. Currently, the functionality is working well, but I am unsure how to validate if any checkbox options are checked with a submit button. Aft ...