Prop validation error: prop type mismatch occurred

My Vue.js countdown isn't displaying the values correctly. Despite defining everything as numbers, I keep getting an error in the console:

[Vue warn]: Invalid prop: type check failed for prop "date". Expected Number, got String.

I've gone through the single file component guide from Vue, but I can't seem to figure out what I'm doing wrong.

app.js

import './bootstrap.js';

import Echo from 'laravel-echo';
import Vue from 'vue';

import CurrentTime from './components/CurrentTime';
import Bitbucket from './components/Bitbucket';
import InternetConnection from './components/InternetConnection';
import LastFm from './components/LastFm';
import PackagistStatistics from './components/PackagistStatistics';
import RainForecast from './components/RainForecast';
import Placeholder from './components/Placeholder';
import Youtube from './components/Youtube';
import ProjectCountdown from './components/ProjectCountdown';
import Countdown from './components/Countdown';


Vue.component('countdown', Countdown);

new Vue({

el: '#dashboard',

components: {
    CurrentTime,
    InternetConnection,
    Bitbucket,
    LastFm,
    PackagistStatistics,
    RainForecast,
    Placeholder,
    Youtube,
    ProjectCountdown,
    Countdown
},

created() {
    this.echo = new Echo({
        broadcaster: 'pusher',
        key: window.dashboard.pusherKey,
        cluster: 'eu',
        encrypted: true
    });
},
});

ProjectCountdown.vue

<template>
<div id="dashboard">
    <Countdown date="March 20, 2017 12:00"></Countdown>
    {{days}}
</div>
</template>

<script>
import Grid from './Grid';
import Vue from 'vue';
import Countdown from './Countdown';

export default {

components: {
    Grid,
    Countdown,
},

props: {
    grid: {
        type: String,
    },
},

data() {
    return {

    }
}
}



// Vue.filter('two_digits', function (value) {
//     if(value.toString().length <= 1)
//     {
//         return "0" + value.toString()
//     }
//     return value.toString();
// });
</script>

Countdown.vue

<template>
<div>
    {{ seconds }}
</div>
</template>


<script>
import Vue from 'vue';
export default {

props: {
    date: {
        type: Number,
        coerce: str => Math.trunc(Date.parse(str) / 1000)
    },
},
data() {
    return {
        now: Math.trunc((new Date()).getTime() / 1000)
    }
},
ready() {
    window.setInterval(() => {
        this.now = Math.trunc((new Date()).getTime() / 1000);
    },1000);


},
computed: {
    seconds() {
        return (this.date - this.now) % 60;
    },
    minutes() {
        return Math.trunc((this.date - this.now) / 60) % 60;
    },
    hours() {
        return Math.trunc((this.date - this.now) / 60 / 60) % 24;
    },
    days() {
        return Math.trunc((this.date - this.now) / 60 / 60 / 24);
    },
},
}
</script>

Answer №1

According to the error message, the issue stems from this specific line:

<Countdown date="March 20, 2017 12:00"></Countdown>

The problem arises because you are passing date as a String, whereas the props expect it to be a Number. This is the validation in place:

props: {
    date: {
        type: Number,
        coerce: str => Math.trunc(Date.parse(str) / 1000)
    },
},

It seems like you're working with Vuejs2 in your new project, where the coerce option has been removed. As mentioned here, you can utilize a computed property like so:

props: {
    date: {
        type: Number
    },
},
computed: {
   modifiedDate: function(){
       return Math.trunc(Date.parse(this.date) / 1000)
   }
}

Now, you can replace usages of date with modifiedDate.

Answer №2

Don't blame Vue for the issue you're facing, it's actually in your code.

You defined date as a number, but then you're passing it as a string... why?

Here's how you declared it:

props: {
    date: {
        type: Number,
        coerce: str => Math.trunc(Date.parse(str) / 1000)
    },
},

And this is how you're using it:

<Countdown date="March 20, 2017 12:00"></Countdown>

Storing dates as numbers may work, but there are better solutions out there.

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

Accessing information from req.files in a TypeScript environment

I am currently using multer for uploading images. How can I retrieve a specific file from req.files? Trying to access it by index or fieldname has been unsuccessful. Even when I log it, I see that it's a normal array, so I suspect the issue may be rel ...

Axios is experiencing challenges in transmitting the cookie

Even after attempting to include {withCredentials: true}, I am still facing issues with sending the cookie to the backend server. return await axios.post(`${API_URL}/posts/category/${id}`, { withCredentials: true }) https://i.stack.imgur.com/Cr8xv.png ...

Adding additional validations to your Marketo form is a great way to ensure the accuracy

I'm having trouble adding a new validation rule to the Marketo form since I'm not well-versed in JS and jQuery. I need this rule to display an error message if the form is submitted with any field left empty. Additionally, I want to validate the ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

When the table is clicked, a dynamic accordion table should appear

My current code displays a table inside another table using a PHP for loop. While I can retrieve the data successfully, I'm facing issues with the UI layout and accordion functionality. The inner table is displaying beside the outer table instead of b ...

Traverse a tree structure of nested child objects in an Angular template using a JavaScript

Check out the Javascript object below: { "id": "1554038371930_ajhnms9ft", "name": "CPS", "nodes": [ { "id": "1554038905938_le34li2cg", "name": "Consumer Journey", "nodes": [ { ...

What is the process for automatically importing unplugin-icons?

After creating a JavaScript project using vue-cli, I encountered an issue with auto-importing ElementPlus and Icons, causing the project to not run properly. How can I resolve this issue and get the project running smoothly? The package.json looks like th ...

Populate a dropdown menu using JSON data

I am working with an SQLite table that has columns for id and name. I have created a JSON array of rows from the autocomplete.php page. Now, I am trying to populate a dropdown list in my select element using this JSON data by utilizing jQuery and JavaScrip ...

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

Struggle with encoding dropdown menu options

I have multiple forms on my webpage and I want to be able to access them all at once and include them in a single large GET request. It's mostly working, but I'm encountering difficulties when dealing with drop down menus because their structure ...

When I disable the select box, I prefer that nothing is currently selected

There is a form where users can input numbers and select the unit of measurement. I need to prevent users from selecting a unit if no number has been entered, and clear the unit value if the number is erased after a unit has been selected. <div> ...

Trouble with Bootstrap 5 Dropdown Functionality

Currently, I am using Bootstrap 5 in conjunction with Django to create a website and I'm encountering difficulties with getting a dropdown feature to work properly. Despite copying the code directly from w3schools, it fails to function when I load the ...

A method to deactivate a button cell after it has been clicked within a for loop

I am struggling with correctly disabling a button in my React code when it is clicked. I attempted to pass in an array and handle the button click, but it consistently results in errors. This task seems more complicated than it should be. How can I ensure ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

Ways to convert asynchronous operations of Node.js into synchronous operations in Node.js

Using node js, I am making multiple AWS API calls within a for loop. var prodAdvOptions = { host : "webservices.amazon.in", region : "IN", version : "2013-08-01", path : "/onca/xml" }; prodAdv = aws.createProdAdvCli ...

What steps should I take to resolve the error: Uncaught SyntaxError: expected expression, received '<'?

I'm facing an issue with my code. It works perfectly on my computer, but when I move it to the server, I encounter the following error. Error: Uncaught SyntaxError: expected expression, got '<' Here is the code snippet causing the prob ...

Trouble encountered while trying to show information on Tooltip using AngularStrap

I've been attempting to show some information in a Tooltip, but all I see is the Title displayed like this: Below is the HTML code where I'm calling it: <button class="btn btn-primary" type="bu ...

Using Angular.js, apply the "visible" class conditionally based on a variable

My Cordova application is built with angular.js and consists of the following 2 files: app.html <div ng-controller="MyAppCtrl as myApp" ng-class="myApp.isWindows() ? 'windows' : ''"> and app.controller MyAppCtrl.$inject = [&ap ...

tips on encrypting css/js file names

Can the filename of the css/js file be encrypted? I have noticed that when I view the source of the website, the filenames of the css and js files look encrypted like this. <link href="/assets/css/builds/73e15c8a3cf6409214bbf8a742e9b5d41403226617.css" ...

Vue3: Utilizing Bootstrap and VeeValidate 4 for Effective Error Message Handling

I am looking to integrate Vue3 with Bootstrap 4/5 and VeeValidate 4. <template> <Form as="form" @submit.prevent="onFormSubmit" class="needs-validation" :class="{ 'was-validated': wasValidated }"> ...