Ways to transfer property values between two instances of a component

Two datepicker components are present, one for "From" date and another for "To" date.

If the "To" date is empty, I want to automatically update it with the value from the "From" date.

I have considered using 'emit' on the value but I am unsure if this is the right approach or how to implement it.

 <datepicker
      input-label="From"
      input-id="start-date"
      input-name="start_date"
      input-value="<%= group_discount.start_date %>"
      @change-date="changeDate"
      >
 </datepicker>
 <datepicker
        input-label="To"
        input-id="end-date"
        input-name="end_date"
        input-value="<%= group_discount.end_date %>">
 </datepicker>


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

Vue.use(Datepicker)

const initGroupDiscount = () => {
  new Vue({
  el: "#js-group-discounts",
  components: {
   Datepicker,
  },
  methods: {
   changeDate(value) {
    console.log("value")
    console.log(value)
    },
  },
 })
}

document.addEventListener("DOMContentLoaded", () => {
  initGroupDiscount()
})





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

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

export default {
    name: "neptune-datepicker",
    props: {
        inputLabel: {
            type: String,
        },
        inputId: {
            type: String,
        },
        inputValue: {
            type: String,
        },
        inputName: {
            type: String,
        },
    },
    data(){
        let value = ""
        if (this.inputValue) {
            const dateParts = this.inputValue.split("-")
            value =`${dateParts[2]}/${dateParts[1]}/${dateParts[0]}`
        }

        return {
            isInput: value,
            isPicker: this.inputValue,
            isOpen: false,
        }
    },
    components: {
        Datepicker
    },
    methods: {
        updateInput(date) {
            this.isInput = date.toLocaleDateString("en-GB")
            this.$emit('changeDate', this.isInput);
        },
        updateCalendar(event) {
            const dateString = event.srcElement.value

            if (dateString.length === 10) {
                const dateParts = dateString.split("/")

                const dateObject = new Date(
                    dateParts[2],
                    dateParts[1],
                    dateParts[0],
                )

                if ((dateObject !== "Invalid Date") && !Number.isNaN(dateObject)) {
                    this.isPicker = dateObject
                }
            }
        },
        blur() {
            this.isOpen = false
        },
        focus() {
            this.$refs.dateinput.focus()
            this.isOpen = true
        },
        mouseOver() {
            this.$refs.dateinput.focus()
            this.isOpen = true
        },
        mouseLeave() {
            this.$refs.dateinput.focus()
            this.isOpen = true
        },
    },
}
</script>

The correct value is emitting to the console, but passing it only to the specific instance of the component for the "To" date remains unclear.

Answer №1

Make sure to pass a prop from the parent component to both data sub-components:

<datepicker
  :myValue="myValue"
  input-label="From"
  input-id="start-date"
  input-name="start_date"
  input-value="<%= group_discount.start_date %>"
  @change-date="changeDate"
>
</datepicker>
<datepicker
    :myValue="myValue"
    input-label="To"
    input-id="end-date"
    input-name="end_date"
    input-value="<%= group_discount.end_date %>">
</datepicker>

You can then utilize that prop in a computed method to check if it has a value and modify the to or from value accordingly.

Note: Another option is to use an emit strategy, but remember to still pass a prop to one of the components for data access. If you are unfamiliar with props, learn more about them here.

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

Trouble encountered while attempting to choose a single checkbox from within a v-for loop in Vue.js?

<div id="example-1"> <ul> <input type="text" v-model="searchString" placeholder="Filter" /> <p>sortKey = {{sortKey}}</p> <li v-for="item in sortedItems"> <input class="checkbox-align" type="checkbo ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

Steering clear of ng-include while still maintaining versatility in displaying sub-templates

In my project, I have a component that serves as a "blog post", containing various data. To accommodate different content sections, I've developed multiple templates that can be dynamically rendered within the main "blog" template using ng-include. H ...

Managing and enumerating array elements in an angular.js controller

In my Angular application, I am working with an array of objects that each contain a "ready" field storing a timestamp. My goal is to determine the count of objects where the "ready" timestamp is earlier than the current time. How can I achieve this? This ...

Retrieving the file name from the line number within the trace stack or Error object

I'm working on enhancing my error handling in Node.js/express. Does anyone know a method to retrieve the filename and line number where an error occurs in my code? error-handler.js, utilizing console.trace, only handles errors at the route level...n ...

A simple program capable of holding two variables

To create a calculator, I want to implement a process where the user clicks buttons to input numbers into a display box. For instance, clicking 3 and then 2 should display as 32 in the input box. After that, if I click on the "+" button, it should remove t ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

Ways to resolve the issue: "internal/modules/cjs/loader.js:638 throw err; ^"

I am encountering an error when trying to run my Vue.js project using npm on localhost:8080. Is there a solution to resolve this issue? This error specifically occurs when I attempt to install node_modules and package-lock.json in my Vue folder, which inc ...

Data update using AJAX and codeigniter was unsuccessful

How can I update my data using Codeigniter and AJAX for submitting the response? Below is the View section of my code: <form id="form_update" action="<?php echo base_url() ?>admin/update_derap_info" method="POST" role="form"> <textare ...

Tips for eliminating duplicate values from an array of objects in JavaScript

I am working with an array of objects where my goal is to remove duplicate values from the values array. I would like the final result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', v ...

Dynamic Element with Mousewheel Event

Simply put, I am attempting to attach a 'mousewheel' event to a div that contains a scrollbar. My code functions properly when used outside of the plugin I developed, but as soon as I convert it into a plugin, it stops working. I tested changing ...

Converting JSON to JS in Django results in an error: SyntaxError indicating a missing colon after the property

I'm trying to figure out how to incorporate a JSON file into a script. I've been unsuccessful in loading it from the filesystem, so I created a view that serves the JSON data directly to the page like this: def graph(request, d): ...

Guide on Vue: Passing custom props and router props

I'm attempting to transfer props from one page to another using a redirect. Check out the code snippet below for the redirect: <router-link :to="{ name: 'shipment', params: { editedItems: getSelected() } }"> Edit Amount ...

Utilizing Vue.js: Dynamically Rendering Components Based on Routes

I needed to hide some components for specific Routes, and I was able to achieve this by using a watcher for route changes that I found in this StackOverflow question - Vuejs: Event on route change. My goal was to not display the header and sidebar on the c ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

Can you increase all px measurements in Notepad++ by a factor of X?

Looking for help with a large HTML image map that contains over 3000 lines of images with specific top/left pixel positions. I'd like to replace these images with larger ones, which would require increasing all the pixel references by a certain amount ...

The art of integrating partial rendering into a template

I'm currently working on a project using Angular 2 and I need to display a partial inside a template without having to create a new component. Is this doable? import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} ...

Error: When attempting to overwrite res.render, a TypeError occurs because the property 'app' is being read from an undefined source

I am working on a project where I need to modify the behavior of the res.render method in order to consistently include an additional option, regardless of any other options present. However, when attempting to implement this modification, I encounter th ...