Ways to retrieve property value from a component in Vue.js 2.0

I am currently working with a specific component that allows for date selection:

<template>
  <div class="animated fadeIn">
      <div class="col-sm-6 col-lg-6">
        <datepicker class="form-control" :value="config.state.fromDate" :disabled="config.disabledFrom"></datepicker>
      </div>
        <div class="col-sm-6 col-lg-6">
        <datepicker :value="config.state.toDate" :disabled="config.disabledTo"></datepicker>
      </div>
  </div>
</template>

<script>
import Datepicker from 'vuejs-datepicker'
var d = new Date()

var year = d.getFullYear()
var month = d.getMonth()
var day = d.getDate()
var fromD = new Date(year - 1, month, day)
var toDD = new Date(year, month, day)

console.log(fromD.toString())
console.log(toDD)

export default {
  data() {
    return {
      config: {
        disabledFrom: {
          to: fromD
        },
        disabledTo: {
          from: toDD
        },
        state: {
          fromDate: (d.getDate() - 1).toString(),
          toDate: new Date(year, month, day).toString()
        }
      }
    }
  },
  components: {
    Datepicker
  }
}
</script> 

My approach in using this component involves importing it like so:

import picker from '../components/DateFilter'

Within my Vue setup, I have a button that is supposed to retrieve a property from the imported component on click event:

<template>
<div class="animated fadeIn">
     <picker></picker>
</div>
<div>
      <button @click="onChange2" class="btn btn-primary">search</button>
</div>
</template>

The method includes an alert to display the value retrieved:

onChange2: function() {
  alert(picker.datepicker.value)
}

Error message encountered:

Cannot read property 'value' of undefined

Further attempts made include:

  alert(picker.data.config.state.value)
  alert(picker.config.state.value)

This issue has been quite challenging for me as a newcomer to Vue. Any assistance would be greatly appreciated.

Answer №1

Accessing child properties using this.$children (or this.$parent) is technically possible, but it's strongly advised not to do so! This method introduces coupling between components, which is something you should avoid at all costs.

Instead, the recommended approach is to utilize props to pass data down to your children and emit events up to your parents. For example, if you are using vue-datepicker, here's a sample code snippet to achieve what you need:

// childcomponent.vue
<template>
  <div class="child-component">
    <datepicker v-on:selected="doSomethingInParentComponentFunction"></datepicker>
  </div>
</template>

<script>
import Datepicker from 'vuejs-datepicker'

export default {
  components: {
    Datepicker
  },
  methods: {
    doSomethingInParentComponentFunction (selectedDate) {
      this.$emit("selected", selectedDate)
    }
  }
}
</script> 

In the parent component:

// parentcomponent.vue
<template>
  <div class="parent-component">
    <child-component v-on:selected="dateSelectedInChild"></child-component>
  </div>
</template>

<script>
import ChildComponent from 'childcomponent'

export default {
  components: {
    ChildComponent
  },
  methods: {
    dateSelectedInChild (selectedDate) {
      console.log(selectedDate)
    }
  }
}
</script> 

If you want to learn more about component communication in Vue.js, check out the provided links or refer to this informative article that covers this topic in depth.

Answer №2

selector is a class for components, not an individual component instance. It does not contain any accessible properties. Similarly, Selectpicker (not selectpicker, which is only the HTML tag form) is a component class, not an instance.

Your approach to Vue data seems to be reversed. While you provide initial values to your selectpickers, you are not storing new values anywhere within them. Instead of trying to retrieve values from children components, it is more appropriate to emit those values out of the children using events (please refer to this link).

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

Turn off automatic zooming for mobile device input

One common issue observed in mobile browsers is that they tend to zoom in on an input field or select drop-down when focused. After exploring various solutions, the most elegant one I came across involves setting the font-size of the input field to 16px. W ...

Understanding the Significance of this Regular Expression

I need assistance with regular expressions as I am not very familiar with them. The issue I am facing is related to a jQuery dynacloud plugin that stops working when a regex match occurs in my code. Can someone please help me understand what this regex mat ...

Does Peerjs exclusively cater to one-on-one webrtc communication?

Can PeerJS be used to implement one-to-many audio communication with WebRTC? I'm currently using Socket.io with Node.js. Is this sufficient for WebRTC integration? As a beginner in WebRTC, could you recommend some options for implementin ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

swapping the final word in a string with Node.js or JavaScript

var str = "Demo Docs Version 1.0.1"; var gotWord = str.split(" ").splice(-1)[0] str = str.replace(gotWord, "testing"); console.log(str); If there is a space between words, I can replace the last word. But how do I replace the last word when ...

There was a problem encountered while trying to load the .json/.csv file

Attempting to grasp D3 through this video has been a challenging experience, particularly when attempting to load an external file. The code snippets are provided below: index.html <html> <head> <meta charset="utf-8"> <title& ...

Guidelines for attaching a div to the bottom of a page?

I have a navigation menu inside div.wrapper, and I am trying to make the div.wrapper stick to the footer. <div class="wrapper"> <div id="menu"> <ul> <li>1.</li> <li>2.</li> ...

What is the right way to integrate VueRouter into a Laravel project?

I'm facing a challenge trying to incorporate VueRouter into my Laravel project. An error message keeps popping up saying "Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the ...

Toggle the image and update the corresponding value in the MySQL database upon clicking

Looking to implement a feature that allows users to bookmark pages in my PHP application using JavaScript. The concept involves having a list of items, each accompanied by an image (potentially an empty star). When a user clicks on the image, it will upda ...

AngularJS can easily interpret and extract information from HTML code

As an example, I have dynamically generated HTML on my webpage like this: <ul> <li>Country</li> <li>State</li> <li>City</li> </ul> I am looking to send this information to the database after clicking a b ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

Keeping the state of a React component intact when navigating back from the router

Imagine you have two React components, A and B. As component A is displayed on the page, the user makes changes that affect some of the states within A. The user then clicks a button to navigate to component B using router.push('/b'). Subsequentl ...

What is a method for capturing the value of a nested input element without requiring its ID to be

Currently, I am facing a challenge in selecting the value of an input box from a user-generated ordered list of text boxes and logging its value to the console. It seems like I cannot find a way to select the value of a child's child element when the ...

Encountering a 404 error when attempting to post from a Node.js express app to a

Trying to post to a MySQL database has been giving me a 404 error. I have searched through various posts here, but none of the accepted solutions seem to work for me. I'm struggling to figure out what I am doing wrong. When utilizing a GET request, t ...

Update the second dropdown menu depending on the selection made in the first dropdown menu

While I know this question has been posed previously, I'm struggling to apply it to my current situation. In my MySQL database, I have a table named "subject" that includes columns for subject name and subject level. Here's an example: Subject ...

Regular expressions for identifying operands and operators in a calculator application implemented with JavaScript

I am currently working on a JavaScript project to create a basic calculator. I am in need of a way to validate each item in an array of operands (sequences of digits) and operators (+, -, *, /, ** for power). I have managed to create regex patterns for di ...

What steps should I take to resolve the issue where Angular project error states that the data path "/polyfills" must be a string?

I am struggling with deploying my Angular app to Firebase and/or running it successfully locally using NodeJS version 18. To access the package.json and source code, you can click on this link: https://github.com/anshumankmr/jovian-genai-hackathon/blob/mas ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Construct a structure containing the key/value pairs of cells within an HTML table row using JavaScript

I'm completely new to JavaScript so please be patient with me; I'm not even sure if I'm searching for the solution correctly. Despite spending hours googling and experimenting, I still can't get it to work. My issue is related to an HT ...

Having issues with Vue 3 Typescript integration in template section

This particular project has been developed using the create-vue tool and comes with built-in support for Typescript. Key versions include Vue: 3.3.4, Typescript: 5.0.4 Here is a snippet of the code to provide context: // ComponentA.vue <script setup l ...