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

A compilation of approved classes for the quill toolbar

The instructions provided in the documentation for the quill module indicate that you can manually create a toolbar using HTML, and then pass the corresponding DOM element or selector to Quill. This will result in the ql-toolbar class being added to the to ...

What steps can I take to incorporate additional arguments into my function?

I am currently working with NodeJS, express, and passport. However, I believe this question is specifically related to JavaScript. Within my routes file, I have the following code: app.get( '/users', login_req, user.index); So, when a get requ ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

I am having trouble retrieving images on my website and displaying URL images

Every time I attempt to retrieve an image URL from the database for the client, I encounter the following error: Refused to load the image 'https://nuclear-photos.s3-ap-southeast-1.amazonaws.com/…22:33:44%20GMT+0400%20(GST)TEST.png' because i ...

VueCropper fails to load properly

After attempting to incorporate VueCropper into my Component, I encountered a few issues: The sourceImg is displayed, but there is no cropbox or preview. When I examine console.log(this.$refs) and console.log(this.$refs.cropper), the results seem contrad ...

Using Vue to access and retrieve the file stored in a local folder

Just a few hours ago, I came across an issue where <a href='path' download></a> was not functioning properly in my Vue project right when I was about to wrap up. After spending almost 4 hours searching for a solution, I couldn't ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

What is limiting me from utilizing the entire Google Calendar feed?

I currently have a public Google Calendar set up. My goal is to retrieve appointment data in JSON format from this calendar. When I utilize the following URL https://www.google.com/calendar/feeds/{calendar_id}%40group.calendar.google.com/public/basic?alt ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

When using Next JS with StoryBook, an error may occur if styles are written in a module.scss file

Every time I try to add some styles to my ButtonWidget.scss file, I encounter an error in the console when running the command yarn storybook Error Code: ERROR in ./src/components/ButtonWidget/ButtonWidget.module.scss 1:0 Module parse failed: Unexpected ...

Guide on setting up a MEAN stack application to run on port 8080

I am brand new to the mean stack development environment. I'm attempting to configure my root domain name to display the app directory once I enter the command grunt, but the only way it currently works is at website.com:8080/!#/. How can I get it to ...

Discovering the Secrets of Laravel 5: Harnessing the Power of Vue.js to Access Data Attribute Values

I'm a beginner in vue js. Within our app, we have implemented validation to check if a value already exists in the database. I would like to enhance this feature by making it dynamic. To achieve this, I have added a data attribute to my field which is ...

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

Different approaches to transforming jQuery code into functional AngularJS code

I am a beginner in AngularJS and I'm looking to implement functionality for a login page similar to the one you see when you click the 'Forgot Password' link: Would it be more appropriate to use a directive instead of a controller for this ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...

Styling Dropdown Options Based on Conditions in React

In my current project, I am attempting to modify the className of selected items within a mapped array using another array (this.props.notPressAble). The reason for this is because I want certain objects in the array to have a different CSS style. handleOp ...

What is the best way to swap out an HTML file with another without altering the link?

I'm working on an HTML file, which is basically a webpage. My goal is to create a functionality where clicking a button will dynamically replace the content of the page with another HTML file, complete with its own CSS, JavaScript functions, and other ...