What is the method for renaming Props in Vue components?

I recently embarked on my VueJS journey and attempted to implement v-model in a component, following an example I found.

<template>
    <div class="date-picker">
        Month: <input type="number" ref="monthPicker" :value="value.month" @input="updateDate()" />
        Year: <input type="number" ref="yearPicker" :value="value.year" @input="updateDate()" />
    </div>
</template>

<script>
    export default {
        props: ['value'],

        methods: {
            updateDate() {
                this.$emit('input', {
                    month: +this.$refs.monthPicker.value,
                    year: +this.$refs.yearPicker.value
                })
            }
        }
    };
</script>

In the parent component:

<template>
    <div class="wrapper">
        <date-picker v-model="date"></date-picker>
        <p>
            Month: {{date.month}}
            Year: {{date.year}}
        </p>
    </div>
</template>

<script>
    import DatePicker from './DatePicker.vue';

    export default {
        components: {
            DatePicker
        },

        data() {
            return {
                date: {
                    month: 1,
                    year: 2017
                }
            }
        }
    })
</script>

I tried changing the name of props from ['value'] to ['abc'] and also updated the template like this:

Month: <input type="number" ref="monthPicker" :value="abc.month" @input="updateDate()" />

However, I encountered an error: TypeError: Cannot read property 'month' of undefined

Answer №1

The issue you are experiencing is a result of using props: ['value'].

To resolve this problem, update the props definition to:

  props: {
    abc: {
      type: Date,
      default: () => new Date()
    }
  },

By making this change, you will have the flexibility to rename the prop as needed.

Here is a link to a working example: https://jsfiddle.net/o5uLxdhs/13/

Answer №2

Have you made any changes to the attribute in the parent component?

parentComponent:

 <template>
  <div id="parent">
   <div is="test" :abc="YearMonth" @input="receiveValueFromChild"></div>
  </div>
</template>

<script>
import test from "./test.vue";

export default {
  components: {
    test: test
  },
  name: "index",
  data() {
    return {
      YearMonth: { month: 1, year: 2018 }
    };
  },
  methods: {    
    receiveValueFromChild: function(val) { //value will be changed by childComponent
      console.log(val);
    }
  }
};
</script>

childCompoent:

<template>
    <div class="date-picker">
        <span>Month: </span><input type="number" v-model="abc.month" @input="updateDate()" />
        <span>Year: </span><input type="number" v-model="abc.year" @input="updateDate()" />
    </div>
</template>

<script>
export default {
  props: ["abc"],

  methods: {
    updateDate() {
      this.$emit("input", { //sending updated value to parentComponent
        month: this.abc.month,
        year: this.abc.year
      });
    }
  }
};
</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

How can I modify the dot colors on a graph using chart.js?

Need assistance with changing the color of graph data points https://i.sstatic.net/QGJBv.png Here is my JavaScript code snippet I have successfully created a graph using chart.js. However, I now want to differentiate data points by displaying different c ...

JavaScript: A guide on sending an uploaded email to a web service in byte array format

Scenario: My website is built using EXTJS6. I have a web service that requires the uploaded email to be sent in byte array format. Inquiry: What is the process for converting a .msg file to a byte array using JS (or EXTJS)? Can we treat it as a simple bin ...

What causes the sudden disappearance of the returned value from AJAX?

This piece of code is what runs on my server: modify_emp.php <?php echo $_POST[id]; ?> Below is the Javascript code in my HTML page: <script> $(document).ready(function () { var alreadyClicked = false; $('.element').h ...

Retrieve the response retrieved from AJAX/jQuery and insert it into the designated form input field

When a user inputs an address into this form and clicks on the verify address button, the following script is executed: $('#verify').click(function () { var address = $('input[name=address]'); var city = $('input[name= ...

Encountering issues with a variable in Vue returning as undefined

I am attempting to extract all the values associated with an object. My challenge lies in utilizing a variable filter to access specific parts of the object. Here is the code snippet I have: getCategoryData(slug){ console.log(this.categories.products. ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Asynchronous requests in Node.js within an Array.forEach loop not finishing execution prior to writing a JSON file

I have developed a web scraping Node.js application that extracts job description text from multiple URLs. Currently, I am working with an array of job objects called jobObj. The code iterates through each URL, sends a request for HTML content, uses the Ch ...

Adjust the width of xAxis[0] and xAxis[1] in Highcharts to their default values

Hi there, I need some help with Highcharts. Is it possible to adjust the width of xAxis[0] and xAxis[1] as well as reset the offset of xAxis[1] at runtime? I have a chart with two x-axes that need to be resized to fit different sized divs. You can see an ...

The URL dynamically updates as the Angular application loads on GitHub Pages

Encountering an unusual issue when trying to access my angular website on GitHub pages. The URL unexpectedly changes upon opening the page. Please check it out at this link: The original expected URL should be However, as the page loads, the URL gets alt ...

Tips for increasing efficiency in Javascript development by leveraging the power of the computer to automate tasks and minimize manual work

When working with JavaScript, what techniques can be used to develop and test efficiently and accurately while focusing on algorithms rather than mechanics? Are there any useful tools that can be utilized in batch or command line mode (outside of an integr ...

Searching for Node.js tutorials using Google API on YouTube

I'm attempting to utilize the Google APIs in Node for a YouTube search. Currently, I'm following a tutorial found here: https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client I've managed to get some basic functiona ...

What is the best way to extract the ID of an element that triggers an OnChange event?

Just a heads up: The solution to my problem ended up being CSS code that was triggered by clicking on a widget. Once I realized it was CSS, along with the widget name and hover action, I was able to handle it successfully. Previous question before the PS ...

What is the process for incorporating vue-turnstile into a vue application?

In my Vue form, I am utilizing vue-turnstile, a dependency that integrates Cloudflare captcha into the form. However, I am encountering an unusual error that I cannot seem to resolve. The warning message reads: [Vue warn]: Missing ref owner context. ...

Designing a mobile user interface for time intervals

Currently, I am utilizing a datetimepicker for inputting a duration of time within a form. While the UI functions smoothly on a desktop, it struggles in a mobile setting. Despite my efforts, I have yet to discover a suitable alternative that seamlessly ope ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

What is the method for sending a file using JavaScript?

var photo = 'http://cs323230.vk.me/u172317140/d_5828c26f.jpg'; var upload_url = 'http://cs9458.vk.com/upload.php?act=do_add&mid=62..'; var xmlhttp = getXmlHttp(); var params = 'photo=' + encodeURIComponent(photo); xmlhttp ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...

Which five key JavaScript concepts should I grasp in order to excel as an AngularJS developer?

Coming from a background of server-side coding, I am delving into the world of AngularJS now. This means I need to have a solid grasp of JavaScript before diving in. If I don't have enough time to master JavaScript completely at the moment, what are ...

How to prevent horizontal scrolling on the right side of a div element

Greetings! I am relatively new to coding and currently facing an issue with stopping horizontal scrolling when the second div is fully visible on the screen (while keeping the third div hidden). Here is the code snippet I have been working on: $(docum ...

What changes do I need to make in order for this code to be compatible with Google Sites?

I am working on creating a random redirect button and need to modify the code below in two ways: <script> <!-- /* Random redirect button- From JavaScript Kit (http://javascriptkit.com) Hundreds of scripts available for free! Please keep this cred ...