skip to Main Content

I’m making a simple VueJS application and I would like to display todays date and time and define it in DefineProps, I’ve tried the following in my component:

I would like to display todays date and time and define it in DefineProps, I’ve tried the following in my component:

<script setup>
const props = defineProps({
  dateandtime: String
})
</script>

And in my view I have the following:

<Header dateandtime="test" />

I also tried putting new Date().toLocaleString() next to the dateandtime prop and I atleast expected something out of it but that didn’t work so easy.

2

Answers


  1. If you want to pass date as props you have to generate your date in the parent component in this case App.vue. The defineProps only serves as an interface to structure our props and define their types, defaults or if they’re required. Depending on how you want to pass your date props, I have defined both String and Date as acceptable prop types in Header.vue. Here is how you can do it:

    App.vue

    <script setup>
    import { ref } from 'vue'
    import Header from './Header.vue';
    
    const todaysDate = ref(new Date().toLocaleString());
    </script>
    
    <template>
      <Header :date="todaysDate"></Header>  
      <Header :date="new Date('December 17, 1995 03:24:00')"></Header>  
    </template>
    

    Header.vue

    <script setup>
    const props = defineProps({
        date: [String, Date],
    })
    </script>
    
    <template>
        <h2>{{ date }}</h2>
    </template>
    
    Login or Signup to reply.
  2. First, update your component to pass the current date and time as a prop:

        <!-- Header.vue -->
    <template>
      <div>
        <p>{{ dateandtime }}</p>
      </div>
    </template>
    
    <script setup>
    import { defineProps } from 'vue';
    
    const props = defineProps({
      dateandtime: String,
    });
    </script>
    

    Now, in the parent component where you use Header, you can calculate the current date and time and pass it as a prop:

    <template>
      <div>
        <Header :dateandtime="currentDateTime" />
      </div>
    </template>
    
    <script setup>
    import Header from './Header.vue';
    
    const currentDateTime = new Date().toLocaleString();
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search