Sharing data between multiple components in VueJS is an essential aspect of building scalable and maintainable

I am struggling with the code I have.

main.js

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

App.vue

<template>
  <div id="app">
    // struggling to pass data to component
    <basics :resume="resume"></basics>
    <education :resume="resume"></education>
    // trying to access values from json file
    {{resumeData.name}}
    {{resumeData.education}}
  </div>
</template>

<script>

import Basics from './components/Basics.vue'
import Education from './components/Education.vue'
import Resume from '../resume.json'

export default {
  name: 'app',
  data() {
    return {
      resumeData: Resume
    }
  },
  components: {
    Basics,
    Education
  }
}
</script>

/components/Basics.vue

<template>
    <div>
        <p>Basics</p>
        // having trouble accessing values from json file
        {{resumeData.name}}
    </div>
</template>

/components/Education.vue

<template>
    <div>
        <p>Education</p>
        {{resumeData.education}}
    </div>
</template>

How can I effectively share data between vue components from the same json file without repeating

import Resume from '../resume.json
in each component?

Your assistance in clarifying this issue is greatly appreciated.

Answer №1

One common and standard approach is to simply use props or import the JSON in each component separately.

However, if you have a large number of components and want to avoid passing the same prop multiple times, there is a clever solution: inject the data globally into Vue.prototype:

Vue.prototype.$resume = {
  name: 'foo',
  education: 'bar',
  ...
}

With this method, all your components can access the data using this.$resume. Just be sure to use it judiciously.

If you encounter similar scenarios, it might be more appropriate to consider using vuex.

Answer №2

When learning about vue.js, there are three unique methods to tackle a problem.

  1. Implement props for data transfer in the Fundamentals and Learning sections
  2. Utilize Vuex for state management
  3. Consider using Event bus for communication

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

The RouterView component seems to be malfunctioning within the Vue project

I recently started working on a vue-project where I created a Home page with a sideBar component and a routerView component. Here's a preview: https://i.sstatic.net/f51tdsZ6.png When clicking on any sidebar item, the router navigates to the corresp ...

What is the best way to fetch images from a JSON object in a React application?

I have been trying to load images from an array of objects in React, but I keep encountering a "module not found" error. This issue has been frustrating me for the past couple of days. Can someone please help me troubleshoot this problem or provide some su ...

Merge two separate Vue applications into one cohesive application

I have developed two separate Vue apps independently from each other. User Interface Admin Interface Each app has its own routes, store, configs, etc. I came across this helpful comment here which discusses treating each app as a component within a mai ...

ES6 scoping confusion: unraveling the mystery

I stumbled upon these two syntax methods for exporting functions. Let's say we have files named actions.js and app.js. The first method looks like this: in actions.js export function addTodo() {} export function deleteTodo() {} and in app.js I have ...

I am struggling to grasp the flow of this code execution

Hi there, I just started my journey in JavaScript learning about two weeks ago. I would really appreciate it if someone could walk me through the execution steps of the code provided below. function sort(nums) { function minIndex(left, right) { ...

Combining multiple datasets in Javascript with a constant value of [0] to calculate the sum

Being a beginner, I am seeking assistance with my variable chartdata that serves as a basis: var chartdata = { labels: [ "Bar 1", "Bar 2", "Bar 3", "Bar 4", ], datasets: [ { label: "Green data", type: "bar", dat ...

The EJS view fails to render when called using the fetch API

Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event: function submitForm(event) { const data = { name, image_url }; console.log(data); fetch('/', { method: &apo ...

Is there a way to include custom headers in the response of socket.io using express.js?

I have been attempting to override the CORS policy using the following code block: app.use('/\*', function (req, res, next) { res.header("Access-Control-Allow-Origin","*") res.header("Access-Control-Allow-Hea ...

Enhancing Azure B2C User Profiles with Vue and MSAL 2.x

After researching Vue specific examples with MSAL 2.x and opting for the PKCE flow, I have encountered difficulties with the router guards executing before the AuthService handleResponse as expected. It seems like there might be an error in my implementati ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...

Transform Python list into a JavaScript array

Seeking quick assistance from experts as I face an intriguing challenge that has me stumped. In a Python .psp file, I have a list mylist[] that is populated at runtime and a JavaScript function that requires a list to dynamically create a form object. The ...

Issue encountered while designing a 3-column card grid with Bulma and Nextjs while fetching data

Trying to implement a 3 Column Card Grid using Bulma in Nextjs with data fetched from a JSON Endpoint. The data retrieval is successful and working perfectly, but struggling to identify the issue. Is there a way to limit the columns? In Bootstrap, used C ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

What is the best way to handle a specific submit button using jQuery/Ajax?

I created a web page with 4 submit buttons that all call the same PHP page process.php using jQuery/Ajax. I trigger this PHP page using the onClick event as shown below: <div class="col-md-12"> <input type="hidden" name="_token" value="<?p ...

The ID update functionality in Node.js is malfunctioning

Hello everyone, I am currently venturing into the world of NodeJS with a goal to create a backend API for a car rental agency. After writing some code to update, view, and delete records by id stored in MongoDB, I encountered a strange issue where it only ...

Sending arguments with $emit is not defined

I am having trouble passing parameters using $emit to filter out my routes in the parent component. It seems that the this.$emit() function is returning undefined on the console. What could be causing this issue? Here is the code from my Home.vue file: &l ...

Require the baseurl to be specified in the config.js file

I am struggling to retrieve the base URL from my config.js file (shown below) because the PHP base URL script I currently have is not functioning properly. Does anyone have any recommendations for an alternative method to replace the PHP base URL in the ...

Why does jQuery not work when attempting to access the HTML of paragraphs within the main content using $('#main-content').children('p'

Hello, I'm still getting the hang of jQuery and Stack Overflow. I'm having trouble understanding the differences between DOM elements. My goal is to update the innerHTML of the <p> element, but I'm encountering some unexpected behavior ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

Subdomain redirection issue with express-subdomain for localhost GET requests

In order to manage requests to specific subdomains, I am utilizing a package in express.js called express-subdomain. From my understanding, the subdomain constructor function requires an express router object that I pass from an exported router module. M ...