Establishing a data variable observer across components in Vue JS

I have two modules: module X and module Y. X.js is structured as follows:

export default {
    name: 'X',
    data () {
        var: true
    }
}

The structure of Y.js is as follows:

import X from './X'
export default {
    name: 'Y',
    components: {
        X
    }
}

I aim to access the dynamically changing value of variable var from module X in module Y. To achieve this, I implemented a watcher:

import X from './X'
export default {
    name: 'Y',
    watch: {
        X.data().var: function() {
            console.log('Value of var changed in X.')
        }
    },
    components: {
        X
    }
}

Despite the mentioned method not yielding the desired outcome. Modules X and Y lack a parent-child relationship, thereby restricting the use of props. How can I address this issue?

Answer №1

If both instances of A and B exist within the same root instance, utilizing that root as an event hub for communication between the two components is possible.

Step 1 | Define the root template that invokes handleAVarChange when necessary:

const rootTemplate = `
    <div class="root">
        <A @var-change="handleAVarChange"></A>
        <B v-bind:AVar="AVar"></B>
    </div>
`;

Step 2 | Implement the Vue root script using rootTemplate:

const root = new Vue({
    template: rootTemplate,
    data() {
        return { AVar: null };
    },
    methods: {

        handleAVarChange(value) {
            this.AVar = value;
        }
    }
});
  • template: Contains the template with A and B.
  • data: Returns an object with property AVar, used to store the source variable from A.
  • methods.handleAVarChange: Serves as an event handler in root.template.

Step 3 | Emit an event named 'var-change' with the new value from A:

export default {
    name: 'A',
    data () {
        return {
            Var: true,
        }
    },

    methods: {
        onSomeEvent(varValue) {
            this.$emit('var-change', varValue);
            // or maybe...
            this.$emit('var-change', this.Var);
        },
    },
}

Step 4 | Ensure that AVar is set as a prop in B:

export default {
    name: 'B',
    props: ['AVar'],
    // ...
}

Answer №2

If you're facing a problem, consider utilizing a basic state management solution (Vue docs).

let store = {
  debug: true,
  state: {
      myVariable: false
  },
  updateMyVariable(value) {
    this.state.myVariable = value
  }
}

Make sure to link the store with components X and Y:

data() {
  return {
    sharedStorage: store.state
  }
}

Explore this JSFiddle for hands-on experience.

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

AngularStrap offers a dynamic and responsive navbar collapsing animation feature that enhances user

I am attempting to replicate the collapsible Bootstrap responsive navbar using AngularStrap. Check out this plunker: <div class="navbar navbar-inverse"> <div class="container" bs-collapse start-collapsed="true"> <div class="navbar- ...

Clear Dropdown Selections prior to Submitting

When trying to change the value of the first dropdown list and reset the second dropdown before submission, I encountered an issue where the second dropdown still retains its previous selection upon submission. There is no submit button as the form is subm ...

How can I pass an Angular parameter to an onclick function?

Let's dive in... I am dealing with a controller $scope.selectedScript = {}; $scope.selectedScript.scriptId = null; $scope.selectScript = function(script, index) { $scope.selectedScript = script; ...

Learn the step-by-step process of clicking on a button to modify its properties and deactivate it

I could really use some assistance. I'm trying to make a button: <v-btn dark color="primary" class="square">Tile 1</v-btn> Is there a way I can modify it so that when clicked, it changes to flat, becomes disabled, and switches its color ...

How can one module in Nuxt mutate the Vuex state of another module?

After trying multiple solutions from the portal without success, I am reaching out here for alternative suggestions. In my Nuxtjs application folder store\modules, I have two modules: ModuleA and ModuleB. I need to access the state from ModuleA in Mo ...

Guide to transferring a Django text field to an HTML attribute and accessing it with JavaScript

Looking to transfer a caption from a Django template to JavaScript for an image? Below is the relevant portion of the HTML code: <ul id="portfolio"> {% for picture in gallery_selected.photo_set.all %} <li><img src={{ picture.path }} a ...

Iterating through objects in an array using JavaScript should only happen after the current object

As an illustration: Starting from [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x0, x2 and x3. And so forth... To [x0,x1,x2,x3] - x0 compares itself to x1,x2 and x3. x1 compares itself to x2 and x3 only. x2 only compares ...

The error message "Uncaught ReferenceError: $ is not defined" in Laravel 7.x signifies that

In Laravel 7.x, I have been experimenting with JQuery. I inserted the following code at the end of the body tag in welcome.blade.php to test it out: <script type="text/javascript"> $(document).ready(function () { alert('JQu ...

Unable to access contextual values in NextJS

When attempting to retrieve values from the context API, I am encountering issues where I receive a default value (without the updates made during the context call) and an undefined value (which should receive a value in the context provider). sortListCont ...

Dealing with Memory Issues in Google Apps Scripts

Currently, I am addressing a challenge within my organization that requires me to maintain some level of ambiguity. However, I have been granted permission to discuss this issue openly. The task at hand involves creating a script to analyze a Google Sheet ...

The mysterious nature of view binding in Ember.js

Here's a unique challenge I'm facing. I've developed a sidebar component called SortableStopView that extends CollectionView. This sidebar contains a scrollable and sortable list of 'stops' which users can click on to navigate to t ...

The Scribd page function is experiencing technical difficulties and is currently not functioning as

I recently added the Scribd document viewer to my website, but I am encountering an issue with the setPage function not working properly. Could someone assist me in setting it up to only display the first 2 pages of the document? Please take a look at the ...

CSS button pressed

I came across a helpful discussion on the topic of CSS for pressed buttons, which provided some answers that I found useful. The link to the discussion can be found here: Pressed <button> CSS. Currently, I have a button within a link and I would lik ...

Is there a way to resolve the error message type issue in Quasar Vuelidate?

I'm utilizing the "vuelidate" plugin for validating the Quasar framework. After writing the code below, I encountered a type error. (property) error-message: string | Ref Type 'string | Ref' cannot be assigned to type 'string | undefi ...

Newbie's guide to setting up babel for material-ui in Next.js!

Helpful Resources: Click here "For better bundle size optimization, create a .babelrc.js file in your project's root directory: const plugins = [ [ 'babel-plugin-transform-imports', { '@material-ui/core': { ...

Restricting the number of characters allowed for text messages and keeping track of the count

I am attempting to implement a character limiter for an html textarea using JavaScript. Additionally, I want to include a total character counter. Unfortunately, the code I have written isn't functioning as expected. Can anyone identify where my mist ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

What's the best way to ensure that the theme state remains persistent when navigating, refreshing, or revisiting a page in the browser?

Is there a way to ensure that my light/dark theme settings remain persistent when users reload the page, navigate to a new page, or use the browser's back button? The current behavior is unreliable and changes unexpectedly. This is the index.js file ...

What causes an undefined symbol in a Linux environment when using a C++ addon in node.js?

As a newcomer to writing C++ addons in node.js, I have created a module called simpleini: $ npm install simpleini This module is based on miniini-0.9 and the source code can be found in src/simpleIni.cc. I have tested this module on Windows, OS X, and Li ...

How can I create a v-slot template with dynamic content in Vue.js?

Hello there! I appreciate you taking the time to read my inquiry. Currently, I am delving into Vue.js, Vuetify, and v-data-table for a project. I am faced with a challenge of getting my v-slot to function with two different strings as the header name. < ...