Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

willbrowning's avatar

Passing date variables between the same nested component

I am using Laravel with Vue and Vue Router, each page for the router is a .vue file.

Inside each .vue page I have the same reused nested component to allow the user to select a desired date range that is used to fetch data from the api.

At the moment I have hard coded the initial start and end dates to be the past 30 days when the date range component is mounted.

So if for example a user selects a date range of the past 6 months but then they navigate to another .vue page then the date range will be back to the past 30 days as the date range component is remounted.

What I would like to do is have it so that the selected start and end dates are passed to the next page so if they select past 3 months then it will remain as this date range even when they visit the other pages.

I have tried a few things with no luck, what would be the best way to achieve this and does it require state management?

Thank you

0 likes
1 reply
willbrowning's avatar
willbrowning
OP
Best Answer
Level 4

For anyone interested, I solved this by doing the following.

in app.js just above the root instance I created a dateRange variable:

var dateRange = {
    debug: true,
    state: {
        startDate: moment().subtract(29, 'days').format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD')
    },
    setDatesAction (startDate, endDate) {
        this.state.startDate = startDate
        this.state.endDate = endDate
    }
};

Then passed this to the root vue instance as below:

var app = new Vue({
    router,
    data: {
        dateRange: dateRange
    }
});

The start and end dates are now accessible from all components by:

$root.dateRange.state.startDate
$root.dateRange.state.endDate

And to change the date range I do the following:

vm.$root.dateRange.setDatesAction(moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD'))

I can also watch for changes so I know when to make a new api call:

'$root.dateRange.state.startDate': 'changeDateRange',
'$root.dateRange.state.endDate': 'changeDateRange'

So now every page component shares the same date range which is exactly what I wanted to achieve.

More info here: https://vuejs.org/v2/guide/state-management.html

Please or to participate in this conversation.