Refreshing a data object that is shared among Vue components

I've recently started diving into Vue, and I've found myself responsible for tweaking an existing codebase. There's this data.js file that caught my attention, containing a handful of objects holding city information, like:

export default {
  nyc:
    cleaning: 3,
    maintenanceS: 1
  }
}

In one specific component, index.vue, the data is brought in just like any typical JavaScript object:

import data from '../components/logic/data'

Now in another component, it's loaded as a prop:

export default {
  data () {
    return {}
},
props: ['data'],
computed: {
...

As per my readings on Vue's documentation, I have a basic understanding of how props are passed down from a parent to child components. Is it safe to assume index.vue acts as the parent component for any other components receiving 'data' as a prop?

I'm trying to enable users to modify the values of the 'data' object using a text box:

<td>Cleaning: <input type="number" v-model.number.lazy="cleaning"/></td>

Am I on the right track assuming that using v-model is the proper way to update these values so they reflect across all components? From what I gather, there's probably some additional JavaScript involved within the component to handle this updating, but I'm uncertain about the approach. How does one go about ensuring the updated value propagates through all components utilizing the 'data' object?

Your insights would be greatly appreciated!

Answer №1

When a parent component has multiple child components, it can send data to them through the use of props. Any changes in the parent component's data will automatically affect the passed data. For example, imagine a parent component with two numbers and two child components - one for calculating the sum and another for multiplying the numbers:

Vue.component('sum', { 
props:["n1","n2"],
template:'<div>Sum => <h3>{{n1+n2}}</h3></div>'

})

Vue.component('mult', { 
props:["n1","n2"],
template:'<div>Mult => <h3>{{n1*n2}}</h3></div>'

})

new Vue({
  el: '#app',
data:{
      num1:0,
      num2:0       
     } 
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
     <input type="number" v-model.number.lazy="num1" class="form-control">
      <input type="number" v-model.number.lazy="num2" class="form-control">
     <span>Parent => ({{num1}},{{num2}})</span>
     <sum :n1="num1" :n2="num2"></sum>
    <mult :n1="num1" :n2="num2"></mult>
</div>

This is a simple example that demonstrates the hierarchical relationship and utility of using props. The v-model directive proves to be very handy when dealing with forms and inputs.

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

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

Different custom background images for every individual page in Nuxt

Looking for a unique background-image for each page in my app is proving to be challenging. Currently, I have defined the background-image in style/app.scss. @import 'variables'; @import 'page_transition'; @import url('https://f ...

Steps for retrieving the selected text from a select element within a Vue component

Currently, I am utilizing Laravel 7 in conjunction with Vue.js 2. One of my current objectives is to capture the selected text when a user changes the chosen option. This snippet showcases my component structure: <template> <div class=" ...

AngularJS Form Validation Error Handling

I am in the process of implementing Form Validation using AngularJS, and I have come across a scenario involving ng-class that is confusing me. Could someone please explain why they are utilizing ng-class in this manner? The presence of a map and an arra ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

Module not defined error

Here is the code for my HTML page: <!DOCTYPE html> <!-- define angular app --> <html ng-app="daily"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" c ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Create 3000 unique squares using a procedural generation method

Looking to build a widget that consists of 3000 squares, but creating them manually would be extremely time-consuming. Does anyone have advice on how to efficiently generate the class .square 3000 times? Additionally, I need to have the ability to customiz ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Enhance the current model in backbone.js by incorporating additional data

When a user selects an item on the webpage, more details need to be fetched and displayed. The API function /api/full_details has been implemented to return the additional data for that item. Challenge: How can I retrieve the additional data and append it ...

Having trouble deciphering this snippet of Express JS source code

Upon reviewing the Express JS source code, I came across the main module where express is being exported. module.exports = createApplication; function createApplication() { var app = function(req, res, next) { app.handle(req, res, next); }; m ...

The Angular MatStepper is unable to detect saved values from two string arrays, although it is able to detect values from a different string array

In my application, there is a MatStepper component that facilitates navigation through the signup flow. A method exists to load cached values when available, causing the MatStepper to skip to Page 2. Subsequently, another method pre-fills the form with the ...

Changing a d3 event from JavaScript to Typescript in an Angular2 environment

I am a beginner in Typescript and Angular 2. My goal is to create an Angular2 component that incorporates a d3js tool click here. However, I am facing challenges when it comes to converting it to Typescript. For instance, I am unsure if this code rewrite ...

Utilizing the keyword 'this' within a function of a JavaScript class that is invoked with the .map method

I am working with the RegisterUser class which contains various methods and properties: class RegisterUser { constructor(username, password, ispublic){ this.username = username; this.password = password; this.ispublic = ispublic; this.id ...

Creating unique identifiers and names for dynamically generated editable HTML table cells using JavaScript

Clicking the button will trigger the GenerateTable() function to dynamically create a table based on selected options from the drop-down menu as column headings. Below is the JavaScript code, along with instructions on how to assign IDs and names to each t ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...