简体   繁体   中英

Communication between Vue.js components on separate pages

I am beginner in Vue.js and I have a question related to communication between Vue.js components which are not on the same page .
I have multiple pages in my Vue.js app and I use router to navigate between them . So I have “Home” page and “Search” page for filtering entities.
On “Home” page I also have less detailed search component and I wanted to use it just as a shortcut for “Search” page, so when user fills input fields and click on button, his search parameters are passed to the search component on “Search” page and "Search" page is displayed and then search is performed. Basically, I just want to send data from that shortcut search component on “Home” page to search component on “Search” page . I tried using event bus and when button is clicked on “Home” page I emit parameters from "Home" page search:

methods:{
        searchApartments: function(){
            
            this.searchParameters.push(this.locationSearch);
            this.searchParameters.push(this.$refs.guestNumberInput.value);
            
            this.$root.$emit("searchApartmentsFromHomepage", this.searchParameters);        
            this.$root.$emit("showAppartmentPage");
        }

and on “Search” page search component I used "mounted" lifecycle hook() to listen to that event bus. Then I would set fields (which are bind to fields in "data" via "v-model") on "Search" page component to values that I got from "Home" page . Then, I would just call search function with these values:

    mounted(){
        this.$root.$on("searchApartmentsFromHomepage", (searchParameters) => {
            this.locationSearch = searchParameters[0];
            this.numberOfGuests = searchParameters[1];
            
            this.filterApartments();
        });
        
    },  

I got everything to work, but input fields on "Search" page are not set to values that I have received from "Home" page. Unfortunately, even though values are passed successfully, they don't appear in fields of my search component and filter function doesn't get any data from them...
Does anyone has idea what am I doing wrong?

Looks like you emit event before Search page subscribed on it.

The easiest solution will be to params in redirect url.

As I understand currently you use redirection /home -> /search

And with search params it will be /home -> /search?param=value&...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM