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

AngularJS controller encounters a scoping problem within a callback function

I have created an angular application with a simple login form that can be viewed on this JSFiddle. HTML Code: <form data-ng-app="jsApDemo" data-ng-controller="loginCtrl"> <label for="username">Username:</label> <input type=" ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

Encountering the error message "Unable to locate module '.nextserverpages-manifest.json'" while attempting to include `babel.config.js` in a Next.js application

During the process of setting up testing for my current next app, we incorporated some new dependencies including jest, babel-jest, @babel/preset-env, @babel/preset-react, and react-test-renderer. We also created a babel.config.js file to configure Babel s ...

Error: Unable to locate module '@material-ui/lab/TabContext' in the directory '/home/sanika/Desktop/Coding/React/my-forms/src/Components'

Hello everyone! I recently started working with ReactJs and I'm currently facing an issue while trying to implement TabContext using the material UI library in React. Upon debugging, I suspect that the error might be related to the path configuration. ...

What are the steps for integrating vue-i18n into a Vue web component?

As I work on developing a Vue web component with vue-cli 3 and the --target wc option, I have encountered an issue. The vue-i18n plugin that I need to use requires certain options to be passed to the main Vue instance as shown below: new Vue({ i18n: n ...

Identifying the differences between a select2 dropdown and select2 multiselect: a guide

I currently have two different controls on my page: a select2 dropdown and a jquery multi value select Select2 Dropdown <select id="drp_me" class="select2-offscreen"> <option value="1">one</option> <option value="2">two</op ...

Providing access to information even in the absence of JavaScript functionality

Is it possible to make the content of a webpage using jQuery/JavaScript visible even when JavaScript is disabled? Currently, I have a setup where clicking on an h2 header will display information from div tags using the jQuery function. I've made sur ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Identifying a change in the source location of an iframe element

I am working with an iframe object that is currently set to a specific page's URL. Here is an example: <iframe src="http://en.wikipedia.org/wiki/Special:Random"></iframe> My goal is to display an alert whenever the location of the iframe ...

Is it possible for one AngularJS application to influence another?

In my latest AngularJS project, I developed an application for user creation. Depending on the selected user type, specific input fields are displayed. Upon submission, the data is sent to the server in JSON format. So far, everything is working smoothly. ...

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Encountered an issue with mapping data from a controller to a view in Angular.js

Currently, my application consists of only three small parts: a service that makes an http call to a .json file, a controller that receives data from the service and sends it to a view. Everything was working fine when I hard coded the data in my service. ...

Is there a way to filter an array of dates without using the map function when a click

After finally grasping how to pass and retrieve data in React, I encountered an issue. I have a click handler called this.SortASC, and when I click on the title, I want to sort the titles alphabetically. However, I'm having trouble getting this functi ...

Despite having a result, the Promise is returning an undefined value

In Vuejs, I have a method named getUsers that takes an array as input and fetches user data from the database. When calling it like this, it successfully returns the results: this.getUsers(executives).then( result => { this.speci ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Updating Angular.js scope after a variable has been modified

On my website, I have implemented a search bar that communicates with a controller receiving JSON responses from the server. The response is stored in a global variable called assetResult. It works as expected initially; however, subsequent searches do no ...

My handleChange function is inaccessible to the event listener

ParentComponent.js (App.js) import React from "react"; import ChildComponent from "./ChildComponent"; import data from "./data"; import "./styles.css"; class ParentComponent extends React.Component { constructor() ...

Utilizing server-side cookies in next.js and nest.js for efficient data storage

I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user shoul ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...