Configuring input properties using props and the <script setup> tag

Is there a way to utilize props to define the input type in a form?

The method below doesn't appear to be effective, are there any alternative approaches?

For instance

<script setup>
defineProps({
  InputType: String,
  InputId: String,
  InputLabel: String,
  InputPlaceholder: String
});
</script>
<template>
  <div class="ml-6 mt-5 mr-6 mb-5 lg:w-1/2">
    <label
      :for="InputId"
      class="block text-sm font-medium leading-6 text-gray-900"
    >
      {{ InputLabel }}
    </label>
    <div class="mt-2">
      <input
        :id="InputId"
        :type="InputType"
        class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-pink-600 sm:text-sm sm:leading-6"
        :placeholder="InputPlaceholder"
      />
    </div>
  </div>
</template>

Answer №1

It is important to carefully review the documentation on how to effectively utilize props with the <script setup> feature. Make sure to assign a value to defineProps in order for props to be accessible within your template.

const props = defineProps({
    InputType: String,
    InputId: String,
    InputLabel: String,
    InputPlaceholder: String,
})
<label :for="props.InputId">{{ props.InputLabel }}</label>
<div class="mt-2">
  <input :type="props.InputType" :id="props.InputId" v-bind:placeholder="props.InputPlaceholder">
</div>

Keep in mind that props can be automatically unwrapped in your template, allowing you to use InputId instead of props.InputId. However, explicit referencing may be necessary if used elsewhere in the <script setup> section.

Answer №2

In the child component, it is recommended to use props with camelCase names such as inputLabel instead of InputLabel:

defineProps({
  inputType: String,
  inputId: String,
  inputLabel: String,
  inputPlaceholder: String
});

These props should then be used in the parent component like this:

<Child input-label="some label"/>
or
<Child inputLabel="some label"/>

VIEW LIVE DEMO

Answer №3

To dynamically render different types of input fields based on a prop called "type."

<script setup>
const props = defineProps({
    type: {type: String, default: ''},
    formField: {type: Object, default: {}}
    }) 
<script>
    
<template>
    <div v-if="type === 'text'">
        Rendering text input here
    </div>
    <div v-if="type === 'file'">
        Rendering file upload input here
    </div>
    <div v-if="type === 'checkbox'">
        Rendering checkbox input here
    </div>
</template>

Answer №4

Here is a simple solution to your query.

If you ever find yourself needing to refresh your Vue component, take a look at this guide on How to force a Vue component to re-render.

const { createApp } = Vue

const MyInput = {
  props: ['type'],
  template: 'Type: {{type}} <br/> <input :type="type" />'  
}

const App = {  
  components: {
    MyInput
  },
  data() {
    return {
      type: 'text',
      types: ['text', 'radio', 'checkbox']
    }
  },
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  Type: <select v-model="type">
  <option v-for="t in types">{{t}}</option>
  </select><br/>
  <my-input :type="type"></my-input>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></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

Tips for connecting a webpage element with endless scrolling functionality

Currently, I am dealing with a webpage that features a container utilizing infinite scroll to load numerous articles. I am faced with the challenge of how to effectively link to a particular article when its corresponding div is only loaded into the DOM u ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Nuxt.js: Streamlining content management systems for a statically generated web platform

When running nuxt generate, the goal is to fetch all collections from the CMS just once since our website is static. However, we are facing challenges in accomplishing this without exposing all content to every route. One approach could be using vuex to s ...

Angular calendar displaying days and dates in a Gantt chart

I am currently navigating the world of AngularJS and I have implemented an Angular Gantt chart from this repository https://github.com/angular-gantt/angular-gantt. However, I noticed that the chart displays dates but it does not display days (Su, Mo, Tu, e ...

A guide on embedding a jpg or png image into an HTML button

I need a button that includes an image. Here is the code I am using: <input type="submit" name="submit" src="images/stack.png" /> However, the image is not displaying on the button as intended. My goal is for the entire button to be the image. ...

When attempting to use the .split method, an error is thrown stating that addEventListener is not

I'm attempting to create a table that automatically fills in the next input when I select options from MySQL. However, when I run this code, I get an error saying "addEventListener is not a function." I'm not very familiar with JavaScript, so I&a ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

What is the best way to incorporate the {id} property into my Next.js dynamic route using the Context API?

I am encountering an issue with passing the ${id} property to my dynamic route [id]>page.jsx, located within the CartItemPage.jsx file. The setup involves using the Context API, similar to React, where I maintain an array of CartItems to render the Cart ...

Articles related to Express.js - encountering issues when attempting to read properties from a null object

I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB. However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category& ...

Adding Data to a Database Using Ajax with PHP

I am trying to use Ajax to insert data into a database, but I keep encountering this error: Uncaught ReferenceError: insertData is not defined at HTMLInputElement.onclick (Modal.php:105) Error screenshot: https://i.sstatic.net/AmXka.jpg The HTML and ...

Is it feasible to develop a functional computer interface using threejs?

Is it feasible to integrate a window into threejs that could facilitate the use of standard desktop applications (such as code editors) within the virtual scene? Please note: This is being implemented within a custom application or a node-webkit environme ...

How can I detect the @mouseup event in a Vue Bootstrap slider?

I have been using a vue-bootstrap slider that comes with two actions, @change and @update. My goal is to capture the final position of the slider once the movement ends. To achieve this, I decided to test both actions. In my scenario, @change triggers ev ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

What could be causing my code to become unresponsive when using a for loop compared to a loop with a specific

After spending a solid 4 hours on it, I finally managed to figure it out. There were no errors popping up, so I resorted to using the debug feature which unfortunately didn't provide much insight. Without any error messages to guide me, I wasn't ...

How to Animate the Deletion of an Angular Component in Motion?

This stackblitz demonstration showcases an animation where clicking on Create success causes the components view to smoothly transition from opacity 0 to opacity 1 over a duration of 5 seconds. If we clear the container using this.container.clear(), the r ...

What is the best way to make a JavaScript cookie remember the state of a DIV?

Seeking assistance with a test site here that is currently in development. I am attempting to make the notification at the top remain hidden once the close button is clicked. Below is my current script: <style type="text/css"> <!-- .hide { displ ...

Tips on transferring multiple elements by dragging and dropping them across various tabs

I am currently experimenting with dragging and dropping multiple elements across different tabs. Check out this JSFiddle. I want to achieve a drag behavior where when one item is being dragged, all other checked items are also dragged along with it, simil ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Utilizing vue-router to create two separate navigation bars where only one link is highlighted as active

In my setup, I have implemented two sections with navigation structured as follows: <ul class="navigation-list"> <li v-for="(route, index) in navRoutes"> <router-link :to="route.path"> <span>{{ route.name }}</span> ...