How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component.

Here's a snippet of my index.html file:

<div id="js-group-discounts">
  <div class="form-group required">
    <datepicker
      input-label="From">
    </datepicker>
  </div>
  <div class="form-group required">
    <datepicker
      input-label="To">
    </datepicker>
  </div>
</div>

And here's what I have in my JavaScript file:

import Vue from "vue"
import Datepicker from "../components/DatePicker"

Vue.use(Datepicker)    
new Vue({
 el: "#js-group-discounts",
 props: {
  inputLabel: {
   type: String,
},
},
components: {
Datepicker,
},
mount: {
console.log(this.inputLabel) // returns undefinend
},
})

This snippet shows the child component, Datepicker:

<template>
 <div >
 <label for="for">label</label>
 <input  type="text"
        class="form-control form-control-info"
        placeholder="dd/mm/yyyy"
        name="this.label"
        id="this.label"
        pattern="\d{1,2}/\d{1,2}/\d{4}"
        required
        v-model="isInput"
        v-on:keyup="updateCalendar($event)"
        ref="startdate"
        @blur="blur"
        @focus="focus">
 <datepicker format="dd/MM/yyyy"
            id="start_calendar"
            input-class="form-control"
            placeholder="dd/mm/yyyy"
            v-model="isPicker"
            :inline="true"
            v-show="isOpen"
            @mouseover.native="mouseOver"
            @selected="updateInput"></datepicker>
  </div>
</template>

<script>
 import Vue from "vue"
 import Datepicker from "vuejs-datepicker"
 Vue.use(Datepicker)

export default {
name: "datepicker",
components: {
Datepicker
},

}

I am struggling to pass this value from the HTML down to a child component. Any suggestions or help would be greatly appreciated.

Answer №1

After reviewing your question, it seems like you are looking for a way for the parent component to access the inputLabel within the <datepicker> child component. Typically, the parent component does not have direct access to the properties of its child components (keep in mind that the inputLabel is a property specific to the child component, and not the parent).

To address this issue, one approach could be:

  • Utilize vm.$emit to dispatch a custom event, such as datepickermounted, when the datepicker component is mounted. The parent component can then listen for this event using v-on:datepickermounted and obtain data from the child component.
  • The payload within the vm.$emit can include the unique ID of the component and the corresponding inputLabel.
  • The parent component maintains an array, e.g., datepickers, to store these emitted data. By listening for the custom event and receiving the data, the parent appends it to its own data collection. Subsequently, the parent gains access to all <datepicker> child components' inputLabel.

var Datepicker = Vue.component('datepicker', {
  template: '#datepicker',
  props: {
    inputLabel: {
      type: String
    }
  },
  mounted() {
    // Notifying parent about the mounting of a new datepicker
    this.$emit('datepickermounted', {
      id: this._uid,
      label: this.inputLabel
    });
  }
});

new Vue({
  el: "#js-group-discounts",
  data: {
    datepickers: []
  },
  components: {
    Datepicker
  },
  methods: {
    storeDatepickerLabel(payload) {
      this.datepickers.push(payload);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="js-group-discounts">
  <div class="form-group required">
    <datepicker input-label="datepickerLabel1" v-on:datepickermounted="storeDatepickerLabel"></datepicker>
  </div>
  <div class="form-group required">
    <datepicker input-label="datepickerLabel2" v-on:datepickermounted="storeDatepickerLabel"></datepicker>
  </div>
  
  <hr />
  
  <ul>
    <li v-for="(dp, index) in datepickers" :key="index">
      <strong>Datepicker id</strong>: {{ dp.id }}<br />
      <strong>Datepicker label</strong>: {{ dp.label }}
    </li>
  </ul>
</div>

<script type="text/template" id="datepicker">
  <div class="dummy">
    I am a dummy datepicker component<br /> My label is {{this.inputLabel}}.
  </div>
</script>


Alternatively, you can opt for using refs to access the component. However, please note that vm.$refs lack reactivity (i.e., if the inputLabel is updated, the change will not reflect).

var Datepicker = Vue.component('datepicker', {
  template: '#datepicker',
  props: {
    inputLabel: {
      type: String
    }
  }
});

new Vue({
  el: "#js-group-discounts",
  components: {
    Datepicker
  },
  mounted() {
    this.$nextTick(function() {
      console.log(this.$refs.datepicker1.inputLabel);
      console.log(this.$refs.datepicker2.inputLabel);
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="js-group-discounts">
  <div class="form-group required">
    <datepicker input-label="datepickerLabel1" ref="datepicker1" ></datepicker>
  </div>
  <div class="form-group required">
    <datepicker input-label="datepickerLabel2" ref="datepicker2" ></datepicker>
  </div>
</div>

<script type="text/template" id="datepicker">
  <div class="dummy">
    I am a dummy datepicker component<br /> My label is {{this.inputLabel}}.
  </div>
</script>

Answer №2

var Datepicker = Vue.component('datepicker', {
  template: '#datepicker',
  props: {
    inputLabel: {
      type: String
    }
  }
});

new Vue({
  el: "#js-group-discounts",
  components: {
    Datepicker
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="js-group-deals">
  <div class="form-group required">
    <datepicker input-label="dealLabel1"></datepicker>
  </div>
  <div class="form-group required">
    <datepicker input-label="dealLabel2"></datepicker>
  </div>
</div>

<script type="text/template" id="datepicker">
  <div class="dummy">
    I am a dummy datepicker component<br /> My label is {{this.inputLabel}}.
  </div>
</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

Modifying button text dynamically during save operation with AngularJS

Is it possible to dynamically change the text on a submit button while data is being saved in a form? Here's an example of the button: <button ng-click="save()">Save data</button> I have updated my save function based on some suggestion ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

Is there an effective way to merge two collections?

I came across an issue where I am attempting to merge two arrays that resemble the ones listed below: var participants = [ {id: 1, name: "abe"}, {id:2, name:"joe"} ]; var results = [ ...

What are some methods for creating a Venn Diagram that includes data within each section using SVG, CSS, or Canvas?

I am attempting to replicate this visual representation using pure SVG, CSS, or Canvas drawing. So far, I have successfully created three circles that overlap and placed a label in the center of each one. However, I'm facing challenges when it comes t ...

What is the best way to adapt a wavetable for compatibility with the `OscillatorNode.setPeriodicWave` function?

I am exploring the use of a custom waveform with a WebAudio OscillatorNode. While I have basic programming skills, I am struggling with the mathematical aspects of audio synthesis. Waveforms are essentially functions, which means I can sample them. Howeve ...

Tips for wrapping text to fit the width of a column

Hello, I have a table with varying column widths as shown below ${"#goldBarList"} table tr td:first-child{width:5%;} ${"#goldBarList"} table tr td:first-child+td{width:5%;} ${"#goldBarList"} table tr td:first-child+td+td{width:6%;} ${"#goldBarList"} table ...

JavaScript timekeepers and Ajax polling/scheduling

After looking into various methods like Comet and Long-Polling, I'm searching for a simpler way to push basic ajax updates to the browser. I've come across the idea of using Javascript timers to make Ajax calls at specific intervals. Is this app ...

FullCalendar dayClick event fails to trigger any action

I'm having trouble implementing the dayClick function in my fullCalendar. Despite setting up the calendar correctly, nothing happens when I click on a day. Here is the code I am using : var calendar; $(document).ready(function(){ app.init(); ...

Verify whether the default export of a file is a React function component or a standard function

Trying to figure out how to distinguish between modules exporting React function components and regular functions. Bun employs file-based routing, enabling me to match requests with module files to dynamically import based on the request pathname. Conside ...

Next.js, Knex, and SWR: Unusual issue disrupting queries

When making API requests using Next API routes and interacting with Knex + MySQL, along with utilizing React and SWR for data fetching, I encountered a strange issue. If a request fails, my SQL queries start to append ", *" to the "select" statement, causi ...

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

Issue with retrieving data from an external provider

I'm attempting to fetch data so I can tokenize my Credit Card, but I am required to use this address: this.state.data.CardRegistrationURL == "https://homologation-webpayment.payline.com/webpayment/getToken" Here is my fetch method: postI ...

Replace .Mui-disabled (or any other pseudo-classes/states) in the MUI v4.1.X theme with custom styling

How can I globally override the default grey background color for disabled items in Material-UI v4.1.x? I know how to do it for specific components like MuiMenuItem, but I'd prefer a solution that doesn't require me to add overrides for each indi ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

Tips for managing encoding when transmitting values through ajax

When working in WordPress, I encountered an issue with an Ajax call where a value was being sent inaccurately. blow = \'blo\ Upon receiving the value on the server end, it appeared to have an extra backslash (\). blow = \\& ...

Tips for converting a large number into a string format in JavaScript

I created this easy loan calculator by following online tutorials and using my basic coding skills. It works well, but I would like to add spaces in the output numbers for readability. For example, instead of "400000", I want it to display as "400 000". ...