Vue event manager, accessible for all components

I have created a new Vue instance and assigned it to the window object, thinking that it would be accessible throughout all components. I expected this setup to allow me access to events emitted anywhere within my application.

However, it seems like this is not working as intended. Can someone provide some guidance?

app.js

window.Vue = require('vue');
window.events = new Vue();
window.app = new Vue({
    el: '#app',
    methods: {
        emit: function (name, params) {
            window.events.$emit(name, params);
        }
    }
});

In an attempt to use the emit method within my components, I added it to my app. Trying to directly call

v-on:change="window.events.$emit('makeChanged', $event)"
resulted in an error stating that window is not defined.

To listen for emitted events from the emit method within my component, I wrote the following:

window.events.$on('makeChanged', function(evt) {});

Edit:

I'm still struggling to make this work...

app.js

Vue.component('models-select', require('./components/results-text/ModelsSelect.vue'));

window.app = new Vue({
    el: '#app',
    methods: {
        emit(name, ...params) {
            this.$root.$emit(name, ...params);
        },
    ...

ModelsSelect.vue

export default {
        props: [ 'endpoint', 'makeId', 'modelId', 'typeId'],
        mounted() {

            this.$root.$on('make-changed', function(evt) {
                console.log(evt);
            });

Within one of my views (add.blade.php)

<select name="make" id="makes" v-on:change="emit('make-changed', $event)" tabindex="2" class="{{ old('make') ? ' is-changed' : '' }}">

Answer №1

If you want to emit and listen for events, you can utilize the $root element.

methods: {
    emitEvent(name, ...args) {
        this.$root.$emit(name, ...args)
    }
}

When using components:

mounted() {
    this.$root.$on('event-name', this.handleEvent)
},
beforeDestroy() {
    this.$root.$off('event-name', this.handleEvent)
},
methods: {
    handleEvent() {
        // implement event handling logic here
    }
}

Answer №2

Avoid using window with v-on::

For more information, refer to the official API documentation:

The expression can take the form of a method name, an inline statement, or can be omitted if modifiers are present.

If you need to access window.events, it's recommended to do so within a method:

<some-element v-on:change="globalEmit('makeChanged', $event)" />
{
  methods: {
    globalEmit(name, ...params) {
      window.events.$emit(name, ...params);
    }
  }
}

You could then move this globalEmit method to a global mixin, rename it to $gemit (for example), and use it universally like this:

<some-element v-on:change="$gemit('makeChanged', $event)" />

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

Error: NextJS cannot access the 'map' property of an undefined object

Hey everyone, I usually don't ask for help here but I'm really struggling with this piece of code. I've tried looking at various resources online but can't seem to figure out why it's not working. Any guidance would be greatly appr ...

Are there any discussions underway about updating JSON standards to officially permit unquoted property names?

Technically speaking, the following JSON is considered invalid: { color: "blue", size: 14 } This is because according to the specification, property names like "color" and "size" should be enclosed in quotes, like this: { "color": "blue", "size" ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

Reflector has no definition in three.js - a software mystery

After implementing the code snippet from the webgl_mirror example, I attempted to add a reflector surface to my scene. It seems that the following code snippet is all that's needed to introduce a reflective object to the scene: var geometry = new TH ...

Node.js cannot access the uploaded image data as it has been defined as undefined

I have encountered an issue while sending an image file through ajax to my Node.js server. Upon attempting to view the file data, it returns 'undefined'. Here is a snippet from my app.js file: var express = require("express"); var app ...

Obtain a fresh SQL identifier post submission through Ajax

When a comment is submitted on a post using ajax, the comment.php script will display the new comment with its own auto-incremented SQL id. It will look something like this: // The $id variable contains the SQL id after data submission <div class="comm ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

Preventing links from functioning on dynamically generated web pages

I have implemented the following code to deactivate all links on a preview page: var disableLink = function(){ return false;}; $('a').bind('click', disableLink); While this successfully disables all static links, any anchor tags loade ...

Creating a cutting-edge mobile application using PhoneGap and Node.js

I have a vision to develop an app similar to a mobile messenger, but I am not a seasoned programmer. My knowledge of JavaScript is at an intermediate level, although I haven't utilized it for any significant projects. The main focus of the app would i ...

Switching Div Elements Created by PHP

Utilizing MySQL, I am fetching data to dynamically generate nested div tags in a hierarchical structure. This structure consists of div tags within div tags within div tags, all uniquely identified through PHP-generated ids: <div class="holder"> ...

Retrieve data from MongoDB that is within the past week in ISO string format

My goal is to retrieve data from MongoDB that is exactly a week old. The specific field I am focusing on is - { _id:821398723913, closed_at:"2020-06-10T01:43:59-04:00" } I am looking to fetch all objects where the 'closed_at' field falls wit ...

Getting the value of a nested object in Vuejs using Laravel

I am currently working with Laravel 8 and integrating the Laravel Spatie package for managing roles and permissions. My goal is to retrieve all admin users along with their respective roles and pass this information to vuejs. $users = Admin::orderBy(' ...

Endless invocation of AngularJS $http requests

Could someone kindly clarify why the $http request is continuously sending an infinite number of requests to the server in my application? The code snippet provided is causing this issue: (function(){ var app = angular.module("GrahamsSocksProducts", [ ...

Images with fadeIn-Out effect on a slide restrict the movement of the div

I am currently working on a project where I have a div named "background" containing 4 images (400x300px) that fade in and out in a row every x seconds. The issue I am facing is that these images are displaying on the top-left of the browser, and I am tr ...

Tips for showcasing the error message from the back-end instead of the status code

After setting up a Backend server and deploying it to Heroku, I have been using the server URL to send and receive data. However, I've encountered an issue where instead of displaying the actual error message, the status code is being returned. Here ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

A guide on utilizing AngularJS to extract data from a webpage

I'm attempting to transfer the information from a specific page on my website and paste it into a file. I know how to post a sample text stored in a variable from Angular and save it in a file in the backend using Node Express, so writing a file isn&a ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Integrating social login using vue-authenticate with passport in a Node.js environment

I've been working on integrating Facebook login with vue-authenticate and passport. Successfully logged into my Facebook account, I obtained the 'Callback code' as well. Here is my callback URL: http://localhost:8080/auth/callback?code=AQD0 ...