How can I pass the value of a variable from one Vue.js 2 component to another?

Here is how I have structured my view:

<div class="row">
    <div class="col-md-3">
        <search-filter-view ...></search-filter-view>
    </div>
    <div class="col-md-9">
        <search-result-view ...></search-result-view>
    </div>
</div>

This is my search-filter-view component:

<script>
    export default{
        props:[...],
        data(){
            return{
                ...
            }
        },
        methods:{
            filterBySort: function (sort){
                this.sort = sort
                ...
            }
        }
    }
</script>

This is my search-result-view component:

<script>
    export default {
        props:[...],
        data() {
            return {
                ...
            }
        },

        methods: {
            getVueItems: function(page) {
                ...
            }
        }
    }
</script>

I am trying to pass the value of the sort parameter (from the filterBySort method in component one) to the getVueItems method (in component two).

Any suggestions on how I can achieve this?

Answer №1

Serge touched on this topic, and I'd like to delve deeper into it. In Vue version 1, components could easily send messages out for others to listen and respond to. However, in Vue 2, the approach is more refined and explicit.

To achieve this communication between existing components, you should create a separate Vue instance to act as a messenger or communication hub that can be accessed by both components. Here's an example using ES5 syntax:

// Create the messenger/bus instance within a shared scope
var bus = new Vue();

// Within your "result" component
bus.$emit('sort-param', 'some value');

// Within your "filter" component
bus.$on('sort-param', function(sortParam) {
    // Perform actions based on the received data
});

If your communication needs are more complex than simple component-to-component interactions, consider exploring Vuex, which is Vue's counterpart to React's Redux.

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

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

The next.js code is functioning properly when run in development mode, but encounters issues when attempting

When using the useAddress() function in run dev, it is returning undefined undefined and then the address when console logged. However, in the run build/start, it only returns undefined. What steps should I take to resolve this issue? import { useAddres ...

The section element cannot be used as a <Route> component. Every child component of <Routes> must be a <Route> component

I recently completed a React course on Udemy and encountered an issue with integrating register and login components into the container class. The course used an older version of react-router-dom, so I decided to upgrade to v6 react router dom. While makin ...

Using Leaflet to beautify categorical json information

As a beginner in coding, I must apologize if a similar question has already been asked. I've spent days searching but haven't found the right combination of terms to find examples for my scenario. I am exploring various small use cases of differ ...

Fading text that gradually vanishes depending on the viewport width... with ellipses!

I currently have a two-item unordered list positioned absolutely to the top right of the viewport. <header id="top-bar"> <ul> <li> <a href="#">David Bowie</a> </li> <li> ...

How can I download a PDF file in React.js using TypeScript on Next.js?

I've created a component to download a PDF file. The PDF file is named resumeroshan.pdf and it's located inside the Assets folder. "use client"; import resume from "/../../Assets/resumeroshan.pdf"; export default function Abo ...

Experience a clean slate with Vue.js 3 after running 'vue serve'

Hey there, I'm having trouble figuring out what's going on. I've tried using two different libraries with no success. I have VueJS 3 installed through Vue Client and it worked fine initially. But when I tried creating a view or component to ...

How do I make the message "document.getElementById(...) is null" become true?

When running my code, only two of the document.getElementById calls (ctx1 and ctx2) successfully get values while the others (such as ctx3) do not. How can I ensure that all elements retrieve their values without receiving an error message? Below is a snip ...

ExpressJS Template Caching System

Encountering issues with template caching in my MEAN app. The navigation bar uses conditional logic to show/hide buttons based on user status. Upon page load, values are null or false until login (views, isLoggedIn). The problem arises post-login - despit ...

Safari is causing issues with HTML5 Video playback

I have a client with a media-heavy website containing numerous video and audio files. While the videos load perfectly on Chrome, Firefox, and IE, they do not load on Safari for Windows. Here's a snippet of the code: <video controls="controls" type ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

JavaScript - Toggling checkboxes to either be checked or unchecked with a "check all" option

To create a toggle checkboxes functionality, I am attempting the following: HTML Code: <!-- "Check all" box --> <input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" /> <!-- the other ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

AngularJS - ng-repeat: Warning: Repeated items found in the repeater and are not allowed. Repeater:

I'm currently using ng-repeat to showcase a collection of items fetched from the Twitter API. However, I am encountering an issue where Angular attempts to display the empty list while the request is still being processed, resulting in the following e ...

What separates $(document).ready() from embedding a script at the end of the body tag?

Can you explain the distinction between running a JavaScript function during jQuery's $(document).ready() and embedding it in the HTML within script tags at the bottom of the body? Appreciate your insights, DLiKS ...

In Backbone.js, specialized events are dispatched to cater to unique needs

In search of a sleek JavaScript animation to have some balls gracefully moving within a canvas, I aim to implement collision detection using custom events managed through Backbone.js rather than resorting to an intricate nested loop to monitor interactions ...

Exploring the power of regular expressions in Javascript when used between

Consider the scenario outlined in the text below I desire [this]. I also desire [this]. I do not desire \[this] I am interested in extracting the content enclosed within [], but not including \[]. How should I approach this? Currently, I have ...

Tips for structuring nested properties in VueJS?

Currently, I'm facing a complex architectural dilemma that's puzzling me. Picture this scenario: 3 components - A -> B -> C. Here, A acts as the grandparent, B as the parent, and C as the child. A passes an array of objects to B. B itera ...