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

Transport the unique identifier of the table row

After retrieving the list of followers from Instagram and storing it in an array in a session, I am displaying the data in a tabular format. <table class="tablesorter" cellspacing="0"> <thead> <tr> <th>&l ...

Struggling to update local state with response data when utilizing hooks in React

I am a beginner using Functional components and encountering an issue with setting the response from an API to a local useState variable. Despite receiving the response successfully, the variable remains empty and I am struggling to figure out how to resol ...

Issue encountered when summing numbers: There appears to be a continuous loop updating within a component's rendering function

Let's say I have a variable initialized as 0 and a method that increments this variable... However, when I try to use them, an error message is displayed: [Vue warn]: You may have an infinite update loop in a component render function. Here is the ...

Having trouble accessing the name property of a select dropdown in Material UI React

Currently, I am facing an issue with implementing a select dropdown. When handling the onChange method, I am encountering a situation where event.target.name is undefined. Specifically, when I choose the 1st option, I want to be able to access 'Englis ...

Exploring the Express problem with AWS SNS web service subscriptions using a Sinatra case study

I'm currently working on developing an auto-subscription API that sends back a token via POST. While I have successfully implemented this in Sinatra (rendering the POSTed JSON from AWS), I'm facing challenges with Express. I believe it's jus ...

What is causing the color to be replaced by the latest selection?

I'm having trouble drawing three lines with different colors. They all end up being the same color, which is the last color specified in my code snippet below: function initObject() { var lineLength = 10; geometry = new THREE.Geometry ...

Combining Array Attributes to Create a New Property as a 'JSON String'

I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute. For example: [{ { "orderNo":"1", "description":"Item 1", "note": "Note 1" }, { "orderNo":"2", "description":"Item 2", ...

Identifying all elements with querySelectorAll and monitoring events with

I am currently attempting to modify this demonstration for page transitions triggered by clicking on links with a shared class. Despite following @ourmaninamsterdam's suggestion here, I am facing difficulties in getting the transitions to work. Can yo ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

Transferring the Build Output of a Docker Container to the Host Machine

My dockerfile is quite simple: # develop stage FROM node:alpine as develop-stage WORKDIR /app COPY package*.json ./ RUN npm install COPY . . # build stage FROM develop-stage as build-stage RUN npm run build I believe that after running the docker contain ...

Executing a function enclosed in parenthesis does not yield any output

My code is supposed to print the sender's name followed by "adopted" and then the first mentioned user. const { Client } = require('discord.js', 'async', 'discord-message-handler'); const bot = new Client(); const cfg = ...

Having issues with TableExport.js exporting Bootstrap HTML tables

I've been trying to use the TableExport.js plugin found at to add Bootstrap HTML table export functionality to my website. I meticulously followed all the steps to include jquery FileSaver, tableExport javascripts, and css. <!-- jQuery --> &l ...

Utilizing "this" in a situation where the function and selector are not combined

When it comes to utilizing this in different scenarios, the results may vary. In example 1, we see that by directly accessing this, we are able to obtain the correct result. $("#my_div").on("click", function () { alert( $(this).attr("id") ) }); Howev ...

"Steady layout of grid for the navigation bar and

Currently, I am in the process of developing a control panel with the use of HTML and CSS. To structure the page, I opted for a grid layout. However, I encountered an issue where the navbar and sidebar do not stay fixed on the screen despite trying various ...

Identifying the HTML elements beneath the mouse pointer

Does anyone know the method to retrieve the HTML tag located directly under the mouse cursor on a webpage? I am currently developing a new WYSIWYG editor and would like to incorporate genuine drag and drop functionalities (rather than the common insert at ...

jquery unbinding events can lead to faster performance

I'm in the process of creating a content-heavy slideshow page that heavily relies on event triggers, with about half of them utilizing the livequery plugin. I'm curious if unloading these events between slides to ensure only the active slide has ...

Why isn't data coming through after sending ajax post requests?

Why am I unable to retrieve data after sending AJAX post requests? During the process of sending an AJAX post request, I use $('#fid1 input,select').attr('disabled','disbaled'); to disable form inputs and then, after a suc ...

Having trouble getting JQuery Ajax POST to work in Codeigniter

Encountering an issue with jQuery AJAX post in CodeIgniter, where clicking the submit button triggers an error. Below is the code snippet: home.js form.on('submit', function(e){ e.preventDefault(); var fields = {}; form.find(' ...

How can React Native efficiently retrieve data from multiple APIs simultaneously?

In my current project, I am incorporating multiple APIs that are interlinked with each other by sharing the same data structure... Below is the code snippet: export default class App extends React.Component { constructor(props) { super(props); } ...