The Vue mixin properties are devoid of content and lack reactivity

Could you please guide me in the right direction if this question has already been asked before? I really hope it's not a duplicate.

I have a Vue application that is compiled using Webpack@NPM. In order to pass a property (roles) across all components, I am using a mixin. The property gets updated with an ajax call when the app is instantiated. However, the issue I'm facing is that the roles only update for the <Root> component and not for any others.

////////////////////////
// app.js
////////////////////////

// import
window.axios = require('axios')
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes.js'

// mixin
Vue.mixin({
    data: function () {
        return {

            // the property in question
            roles: [],
        }
    },

    methods: {
        getRoles: function() { //////////// this method updates the property.
            // fetch
            axios.get('/api/vcr/admin/roles')

            // process
            .then(response=>{
                this.roles = response.data.data;
            })

            // error handling
            .catch(error=>{
                this.toast(error.response.data.message);
            })
        },
    },
});

// router
const router = new VueRouter({
    mode: 'history',
    routes:  routes,
});

// app
const app = new Vue({
    el: '#app',
    components: { App: require('./views/App').default },
    router,
    base: '/saas/vcr/admin',

    created: function() { ////////////// I update it here
        this.getRoles();
    }
});

////////////////////////
//  Foo.vue
////////////////////////

<script>
    export default {
        mounted: function() {
            console.log(this.roles) ////// returns an empty array
        }
    }
</script>

Is there a way to make the roles property reactive throughout all components?

Answer №1

Your global mixin doesn't actively populate the roles property; instead, it expects inheriting instances to handle this task. While your "root" instance in the app does call getRoles during the created lifecycle hook, the component Foo does not, resulting in a default empty value for its roles. Keep in mind that each component manages its own version of the roles property and requires individual population. To address this issue, you could enhance the mixin by incorporating the created lifecycle hook, similar to how it's implemented in the root instance. You can refer to this example for guidance. However, be cautious as executing an API call for every component creation may not be ideal behavior. If your goal is to populate the roles property once and share it across all components, consider utilizing Vuex to establish a centralized global state. This way, roles can be managed uniformly and efficiently shared among all components in a reactive manner.

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

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

Tips for maximizing website performance on touch-enabled devices

When using a touch device such as an iPhone, iPad, or Android device, it can be challenging to accurately tap on small buttons with your finger. So far, there is no universal method in CSS media queries to detect touch devices. As a workaround, I check if ...

Generate unique IDP SAML replies

Currently, I am working on creating unit test cases for validating SAML responses. To achieve this, I am seeking guidance on generating multiple SAML responses in XML format using the necessary certificates and private keys. Are there any Node.js librari ...

javascript passing a window object as an argument to a function

In Slider function, I am passing a window object that does not contain the body element. Additionally, my code only functions correctly on mobile screens. While debugging the code below: console.log(windows.document); If (!mySlider) {console.log(windows. ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

What is the process for integrating a custom script prior to building in a react application?

I am facing an issue with the Chart library that I am using and in order to resolve it, I need to execute a specific script. The script can be found at this link: https://github.com/plouc/nivo/blob/master/scripts/patch-react-spring.js. I have considered ad ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

Form validation in AngularJS for controllers with multiple instances

My specific needs In order to meet the unique requirements of my business, manual validation is necessary. The validation rules can vary in strictness depending on the context in which a specific screen is accessed. It is also important to note that ther ...

Step-by-step Guide to Setting pageProps Property in Next.js Pages

When looking at the code snippet provided in .../pages/_app.js, the Component refers to the component that is being exported from the current page. For instance, if you were to visit , the exported component in .../pages/about.js would be assigned as the ...

At what point is the args variable required by Dojo?

There comes a point when passing the args variable to an anonymous function in Dojo becomes necessary, even though the function itself may not visibly need it. This can lead to confusion as there is no clear indication on the Dojo help page regarding whe ...

Populate Vue 3 Element-plus Virtualized Table with actual data

As a newcomer to frontend development, I am currently working on integrating Element-plus Virtualized Table with actual data. Here is the basic structure of the example: const generateColumns = (length = 10, prefix = 'column-', props?: any) => ...

Tips for utilizing both the Element Selector and Class Selector in Jquery

I am working with a simple table that has TDs assigned either the 'PLUS' or 'MINUS' class. My goal is to use jQuery to implement functionality for collapsing all or expanding all. When the Expand All button is clicked, I need to chang ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wr ...

Dealing with an Undefined Property: Troubleshooting Guide

Encountering an error message Uncaught TypeError: Cannot read property 'top' of undefined at VM32939 own.js:819 resulting from var hands_corrected = (hands_original.top + 680) this issue arises because "hands_original" is not used in any par ...

"Troubleshooting ng-submit in AngularJS: How to Fix a Function That

I've encountered an issue with my angular-promise where a http method is not being called when a form is submitted using ng-submit. There are no errors, but it seems like the function is never executed. Here's the JavaScript code snippet: myapp. ...

Does creating a form render the "action" attribute insignificant in an AJAX environment?

When submitting forms exclusively through AJAX, is there any advantage to setting the action attribute at all? I have yet to come across any AJAX-form guides suggesting that it can be left out, but I fail to see the purpose of including it, so I wanted t ...

The transparency of an image is being lost when it is used in a modal

I am facing an issue when trying to append a modal that contains only a transparent gif. The problem arises when the transparent background of the gif is not displayed properly. There seems to be no issue with the transparency settings of the gifs themselv ...

Why won't the state change when using Angular's ui-router $state.go method?

I have developed a factory that is responsible for detecting state changes and checking if a form has been modified. When the form is dirty, a modal window like a confirmation prompt should appear. However, I am encountering an issue where the $state.go() ...

Display information in a paginated format using components

As a newcomer to React, I may use the wrong terms so please bear with me. I am attempting to implement pagination for an array of components. To achieve this, I have divided the array into pages based on the desired number of items per page and stored eac ...