Can properties be modified in a nested child component within vue.js without requiring a sequence of events throughout the entire hierarchy?

In various instances, it has been advised against mutating properties in vue.js, as it is considered an anti-pattern. Even mutating object properties or using functions like this.$set to add elements to an object that is given as a property is discouraged.

Given this, what is the correct way for a component to modify data it receives? While vue.js recommends emitting events as a pattern, consider this fictional scenario:

// Main Component
<template>
   // content skipped for simplicity
   <some-component :someObject="something" />
</template>

// SomeComponent
// Passes this data to another component
<template>
    <another-component :someObject="someObject" />
</template>

// AnotherComponent
// Does things using someObjet

Let's say the third component, AnotherComponent, is responsible for displaying data passed down from the main UI and potentially passing it (or parts of it) to other components as well.

Does this mean that any component wanting to modify the data (e.g., a delete button in a list) must emit an event, which then all components in the hierarchy must listen for and pass up to the original component, the only one permitted to directly mutate the object?

Is there a more efficient method for accomplishing this?

Answer №1

Instead of linking events together to connect parent and deep child components (or communicate between deep ancestors/siblings), for straightforward situations, you can utilize an event hub. (For more intricate scenarios, refer to Vuex.)

You would establish a global variable:

var eventHub = new Vue(); // using a Vue instance as the event hub

To trigger events, you could use it in any component:

eventHub.$emit('myevent', 'some value');

In another component, you would then listen for that event. The action associated with the event might be anything, including a function that modifies the data:

mounted() {
    eventHub.$on('myevent', (e) => {
        console.log('myevent received', e)
        this.someDataProperty = 'newValue' + e;
    });
}

Demonstration:

... (Demo code shortened for brevity) ...

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

Navigation buttons that move the user either up or down the page

I am a beginner in programming and I wanted to create two buttons for my webpage. One button should appear when the page is scrolled more than 300px and take the user to the top, while the other button should be displayed immediately and scroll the user to ...

Is there a way to retrieve the real-world position in threeJS without having a mesh directly under

code.js // ... this.width = 2000 this.height = 2000 // ... this.camera = new THREE.OrthographicCamera(this.width / -2, this.width / 2, this.height / 2, this.height / -2, 1, 1000 ); this.camera.position.z = 100; this.camera.position.x = 600; this.camera.p ...

Is there a way to locate and refine the blogs associated with a specific user?

Check out the following blog entries stored in the Database: [ { _id: 5fec92292bbb2c32acc0093c, title: 'Boxing ring', author: 'T. Wally', content: 'boxing stuff', likes: 0, user: { _id: 5fd90181 ...

It is not possible to alter data within the @change event handler in Vue.js

In this particular component, there is an input[type=file] element. Additionally, within this field, there is an uploadFile handler that invokes the validateMessage method in an attempt to modify the error message displayed. While it appears that after c ...

Perform a replacement with jQuery.replaceWith() on an input field and refocus in Microsoft Internet Explorer

There exists a script http://gist.github.com/457324 which establishes default text (extracted from the element's title attribute) for empty input[type=text] as well as input[type=password] elements. However, setting default text for password elemen ...

There is an issue with the Angular front-end receiving errors while trying to access the API on the C

In my current setup, I have an Angular front-end communicating with a C# webAPI back-end. The Angular application is able to fetch data from external URLs like and json-server --watch db.json. On the other hand, the C# webAPI successfully responds to API ...

Guidelines for creating numerous self-edges within a node-link diagram using D3

Creating a single self-link on a node within a node-link diagram can be accomplished by following the instructions outlined in this resource: D3 Force Layout Self-Linking Node If you need to draw multiple links on the same node, what modifications would y ...

Using npm link with Webpack results in eslint errors

I have a multi-package project setup, where I have one JavaScript package that depends on a TypeScript library. Initially, I was using Sinopia and had to reinstall the TypeScript library every time I made changes to it. Then I discovered npm link and thoug ...

Clarifying the confusion surrounding AngularJS $q, promises, and assignments

Curious about a particular behavior I'm witnessing. Unsure if there's a misunderstanding on my part regarding promises, JavaScript, or Angular. Here's what's happening (I've prepared a plnkr to demonstrate - http://plnkr.co/edit/ZK ...

Utilize AngularFire to generate a new User and invoke the factory function to showcase notifications

I recently started working with AngularJS and wanted to integrate it with AngularFire/Firebase for storing project data. I created a factory that manages notifications to be displayed in a centralized location. Here is the structure of my factory: myApp.f ...

What is the process for changing a field in a document on firestore?

Is there a way to modify a specific field in a firestore document without retrieving the entire document beforehand? ...

jQuery tooltip box not functioning correctly

When the mouse enters on li a, the tooltip box (class .show_tooltip) is appearing on the left. I want each tooltip box to display just above or to the left of the link that the mouse is on. The links need to stay on the right as they are now, so please do ...

Implementing form validation and data constraints for a vehicle's license plate number and date with CodeIgniter

I have a working code but I need help with form validation. The validation should check the delivery table for "vehicle 1" appearing 5 times on the same delivery date. If this condition is met, an error should be alerted indicating that Vehicle 1 can only ...

I require a breakdown of the JavaScript code, please

Are you struggling with a code snippet that involves CSS, JavaScript, and HTML? Let's take a look at the complete code: <!doctype html> <html> <head> <link rel="stylesheet" type="text/css" href="http://snipplicious.com/css/bo ...

Enhance Your VuePress Experience with Unique Sidebar Contents for Every Single Page

I am in search of a way to personalize links and sidebar on each individual page, avoiding the rendering of headings as table of contents. My aim is to have custom content displayed like this: Node JS -Lecture 1 Introduction --Sub Lecture -Lecture 2 Basic ...

Unlocking the Power of useContext in Next.js with TypeScript

I am facing challenges with using useContext to provide data. While I understand how to implement useContext in React, I have been struggling to do the same in Next.js with TypeScript. Could someone please assist me? Below is my _app.jsx code: import { Ap ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

How can custom CSS and JS be loaded in Sencha Touch based on the user's device - PC, tablet, or smartphone?

Is there a way to configure a webpage so that when the user is accessing it from a PC (using Safari/Chrome/Firefox), they see the "normal" version of the page, but if they are using an iPad to view the same URL, they get Sencha Touch (css, js) files in t ...

Unable to scroll after the webpage redirects

I am currently working on developing a website for uploading images with a comment feature. The comments section is displayed below the image in the 'imagedisplay.php' file. If a user is not logged in, they are redirected to the sign-up page and ...