Unconventional behavior in Vue.js involving the window object

Upon initializing my vue.js 2.0 application, I create a window.User object.

Everything seems to be functioning correctly. However, I encounter an issue when trying to use it in some components within my templates:

v-if="this.User.role == 2"

In some components, this works perfectly fine while in others it throws an error (

Cannot read property 'role' of undefined
). How is this even possible? To troubleshoot, I attempted the following in the problematic components:

created() {
    alert(window.User.role);
}

Surprisingly, the expected result appears! But for some reason, it doesn't work within the template. What could be causing this discrepancy? It's quite frustrating.

In my bootstrap.js:

window.User = Laravel.user;

I register all my components in a similar manner:

Vue.component('corporations',           require('./components/corporation/Corporations.vue'));

Answer №1

If you have a variable named User that behaves like a global variable and you need to access it in all components while ensuring reactivity, one approach is to add it to the root Vue's data and then reference it as this.$root.User in other components.

Another option is to use a mixin to define a computed property that will make the User variable available to all components utilizing the mixin. Here's an example:

var mixin = {
    computed: {
        User: function () { return window.User; }
    }
}

Using the mixin is probably the preferred method in this case.

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

Tips for swapping out a new line character in JavaScript

Hello! I'm currently facing a challenge with some code. I have a function designed to replace specific HTML character values, such as tabs or new lines. However, it's not functioning as expected. var replaceHTMLCharacters = function(text){ tex ...

Creating a production build with sourcemaps in Angular using the CLI

How can I preserve sourcemaps after the production build process? Currently, my command appears as follows: "build-prod": "ng build --app=release -prod && cp -R lang dist" I attempted to modify it to: ng build --app=release --sourceMap=true -prod && cp ...

Event delegation will be ineffective when the target element is nested within another element

After receiving a recommendation from my colleagues on Stackoverflow (mplungjan, Michel), I implemented the event delegation pattern for a comment list. It has been working well and I am quite excited about this approach. However, I have encountered an iss ...

The error message "writeUserData is not defined" is indicating that there is an undefined variable in the react code

I'm still learning React and I've been working on a new function: This is my code in summary: class Signup extends Component { constructor(props) { super(props); } componentDidMount() { } writeUserData = (userId, username, email) => ...

the modal body is taking longer than expected to load with ajax

I have a unique modal that I'm filling with dynamic data through an Ajax GET request upon modal load. Interestingly, the data is not fetched or added to the modal body unless I trigger an alert first. The structure of my modal is as follows: <div ...

Tips for transferring parameters to functions within middleware

Attempting to pass a parameter to a middleware has presented some challenges for me. Within the routes' handler, I have the following function: router.get('/users', auth.required, userController.findAll); This function then leads to the a ...

Incorporating marker tags to different sections of text within a contenteditable div

The main objective of this feature is to enable users to select placeholders within message templates (variable names enclosed in %). Inspired by Dribbble The API provides strings in the following format: "Hello %First_Name% %Middle_Name% %Last_Name% ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

Ensure that each number is entered only once in the input field

Is there a way to use javascript/jquery to prevent a user from entering the same number twice in an input box? Users can enter multiple numbers one at a time, but I need to notify them or take action if they try to input the same number again. I attempted ...

Change the locale on the current path with a query in Next.js by utilizing the router

Managing locale changes centrally can be tricky. When a user selects a new locale from a list, I use useRouter to redirect them to the current page in the selected locale like this: var router = useRouter(); const changeLocale = (selectedLocale) => { ...

Encountering `No provider for ControlContainer!` error while utilizing [class.someClass] in Angular 2?

I have a project in progress which involves using angular 2. I am currently working on forms and validation and have encountered an issue. Although I have found a workaround, I am curious to understand why my original code is not functioning properly. Bel ...

What is the best way to create an animation for a dynamic menu background image

While hovering over a list item, I want to create an animation where the background image appears to zoom out. $(function () { var image = $('.menu').find('img').attr('src'); $('.menu ul li').mouseover(fun ...

CreateJS does not support the use of addEventListener

Recently, I've been diving into learning CreateJS, but I've hit a roadblock. The eventlistener I'm trying to add doesn't seem to be working as expected. The messages from addKey() and removeKey() functions just won't display. func ...

None of the Views are rendered after executing RedirectToAction

I created a Login Page that redirects to the required page after validation. However, when it redirects, the previous Login page view appears instead of the expected view. Below is the JavaScript code I am using: function abc() { var email = ...

Troubleshooting RangeError in AngularJS $routeParams: Exceeding maximum call stack size

While using AngularJS v1.5.9 and $routeParams, I am encountering repetitive errors in the console of my Chrome browser. RangeError: Maximum call stack size exceeded at la (angular.js:10097) at p (angular.js:9492) at g (angular.js:8757) at ...

Assign a variable within a Vue composition file

I'm diving into the world of composition API in Vue and I'm uncertain if my approach is breaking any established patterns. I have a desire to initialize a variable directly within the composition file: GameLogic.ts export default function () { ...

Combining VueJS with jQuery DataTables

I have integrated jquery-datatables with vuejs in my project. It works fine when displaying less than 500 records, but as soon as I try to fetch more than 500 records, the filters stop working and the message "No data available in table" is displayed at th ...

Tips for triggering a click event on a DOM element using Angular 2

How can I automatically load a component upon loading? <app-main id="tasks" [(ngModel)]="tasks"></app-main> Here is the function call from JavaScript: public tasks; ngOnInit() { this.tasks.click(); } I have attempted using document.getE ...

Switch Tabs with Dropdown Selection

I came across a website with a similar feature, but I am interested in using a dropdown menu instead of a button or link. Check out this webpage for reference The problem seems to be related to this line of code: onchange="$('#'+$this).tri ...

Retrieve the html form id using javascript that is written in C# language

Within my application, there is an HTML form. <form id="abc_form" method="post"> </form> I am looking to assign an action to this form and then submit it. I want something like: abc_form.action='full path of next page' abc_form. ...