Sending information between components in VueJS

I recently created something new for myself, but I encountered a problem. Let me explain further.

The component is named components/HomeComponent.vue

Here is the code:

HomeComponent.vue

<script>
export default {
  name: "HomeComponent",
  data() {
    posts: [
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" }
    ];
  }
};
</script>

and I have my "view" views/Home.vue

Home.vue

<template>
  <!-- Blog Entries Column -->
  <div class="col-md-8">
    <h1 class="my-4">Статии</h1>

    <!-- Blog Post -->
    <div class="card mb-4" v-for="post in posts">
      <div class="card-body">
        <h2 class="card-title">{{ post.title }}</h2>
        <p class="card-text">{{ post.body }}</p>
        <a href="#" class="btn btn-primary">Read More &rarr;</a>
      </div>
      <div class="card-footer text-muted">
        Posted on January 1, 2017 by
        <a href="#">xxx</a>
      </div>
    </div>
  </div>
</template>

I need to access the posts in my Home.vue file and create a loop. Can anyone provide guidance on how to do this? Thank you in advance! :)

<script>
// @ is an alias to /src
import HomeComponent from "@/components/HomeComponent.vue";

export default {
  name: "home",
  components: {
    HomeComponent
  },
};
</script>

Answer №1

To solve the issue, you'll need to pass your data down as props to the Home component. For more details, check out the documentation here. However, here's a quick solution for your problem.

Comp.vue

<template>
  <!-- Blog Entries Column -->
  <div class="col-md-8">
    <h1 class="my-4">Articles</h1>

    <!-- Blog Post -->
    <div class="card mb-4" v-for="post in posts">
      <div class="card-body">
        <h2 class="card-title">{{ post.title }}</h2>
        <p class="card-text">{{ post.body }}</p>
        <a href="#" class="btn btn-primary">Read More &rarr;</a>
      </div>
      <div class="card-footer text-muted">
        Posted on January 1, 2017 by
        <a href="#">xxx</a>
      </div>
    </div>
  </div>
</template>

<script>
 export default {
   props:['posts']
 }
</script>

HomePage.vue

<template>
  <comp :posts="posts"></comp>
</template>

<script>
import Comp from './components/Comp.vue'
export default {
  name: "HomeComponent",
  components: {
    'comp': Comp
  },
  data() {
    posts: [
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" },
      { title: "Hello", body: "Some text" }
    ];
  }
};
</script>

Answer №2

Child components receive data through props, and you can use emit to send data back to the parent component.

data() {
  posts: [
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" }
  ];
},
mounted () {
  this.$emit('posts', this.posts);
}
  

To handle this in Home.vue, you need to listen for the event change like this:

<template>
  <div>
    <HomeComponent v-on:posts="getPosts($event)"></HomeComponent>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        posts: []
      }
    },
    methods: {
      getPosts(e) {
        this.posts = e; 
      }
    }
  }
</script>

Answer №3

HomeComponent.vue

<template>
  <div>
    <slot :posts="posts"></slot>
  </div>
</template>
<script>
 export default {
 name: "HomeComponent",
 data() {
  posts: [
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" },
    { title: "Hello", body: "Some text" }
 ];
}
};
</script>

Home.vue

<template>
    <div>
        <home-component slot-scope="{ posts }">
            <div class="card mb-4" v-for="post in posts">
               <div class="card-body">
                 <h2 class="card-title">{{ post.title }}</h2>
                 <p class="card-text">{{ post.body }}</p>
                 <a href="#" class="btn btn-primary">Read More &rarr;</a>
               </div>
               <div class="card-footer text-muted">
                 Posted on January 1, 2017 by
                 <a href="#">xxx</a>
               </div>
             </div> 
        </home-component>
    </div>
</template>
<script>
import HomeComponent from "@/components/HomeComponent.vue";
export default {
  name: "home",
  components: {
    HomeComponent
  },
};
</script>
  

https://medium.com/binarcode/understanding-scoped-slots-in-vue-js-db5315a42391 https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots

Answer №4

Your component has its own data that is specific to it. To pass this data to other components or views, consider keeping it in app.vue and accessing it directly from there. Alternatively, you can centralize your data access by using VueX (data store), which allows for manipulation of larger amounts of data at a more advanced level.

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

Nuxt generate encountered a 500 error during execution

My Nuxt app pulls data from a Wordpress REST API, and when I run `nuxt generate`, approximately 100 pages are generated simultaneously. However, around 80% of the API calls made during this process fail with a status 500 error. https://i.sstatic.net/J8975 ...

Displaying all divs when the checkboxes are unchecked

My code displays a product list with various details stored in different divs based on data attributes like brand, store, and more. A friend helped me develop a filter using checkboxes for record selection. However, I need to make a small modification to i ...

Display loader while waiting for file to be loaded

I am utilizing ajax to retrieve a file. The loading animation is functioning properly with the ajax request, however, the file size is notably large. I am interested in implementing a preloader that will display until the file has finished loading. ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

I'm having trouble getting a http.request to run within an imported module. It just doesn't seem to work when I try to access

Here is the code from my main.js file: var spaceJson = require('./space.js'); var options = { "method": "GET", "hostname": "10.10.111.226", "port": null, "path": "/API/Org", "headers": { "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJ ...

Is Postman cooperating, yet Ajax is not playing nice?

I am facing an issue while trying to make a GET request from a server that stores some account data. The request needs an Authorization header for it to work properly. I was able to retrieve the data successfully using Postman, but when I tried doing the s ...

When attempting to incorporate a video using Sencha, an error occurs stating that the resource is being interpreted as an image but is being

While attempting to incorporate a sample into Sencha, I encountered an error stating "Resource interpreted as Image but transferred with MIME type text/css". Ext.define('MyApp.view.Newpage', { extend: 'Ext.Video', xtype: ' ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...

jQuery enigma - struggling to get slideUp/slideDown to function

My goal is to utilize jQuery and CSS to display the initial paragraph out of a set of four, and insert a link or button at the conclusion of the first paragraph. Upon clicking on the link or button, my aim is to reveal the remaining three paragraphs in a s ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

Troubleshooting the AngularJS digest error within a hybrid application

My hybrid app is quite bulky, using angularjs 1.7 and angular 5.x simultaneously. I have integrated ngUpgrade module to manage both apps, but I encountered a problem when trying to navigate to a different route using href, which is causing the digest cyc ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

Comparing arrays of numbers in PHP

I am faced with the following scenario: $input = ['1, 2, 3, 4, 5']; I'm looking to extract each individual number from the array, which are all stored as a string. Is there a way to accomplish this task using foreach() or any other method ...

Navigating from Laravel Jetstream to a Vue file using the Inertia route

I am in the process of setting up a route in Laravel Jetstream using Inertia. I want the route to be /bloglist. The Vue file can be found at /resources/js/Blog/BlogList.vue Here is the route code I am using: Route::inertia('/bloglist', 'Bl ...

Create a duplicate of an object in Vue.js by utilizing the script tag or storing it inside the instance,

Curious about the best practice for handling this code and understanding the difference between cloning an object inside a script tag versus doing it in a data property: <script> import {cloneDeep} from "lodash"; import {INVITE_USER_FORM_FIELDS} ...

What is the best way to package JS files in an asp.net framework?

In my Angular application, I am dealing with numerous JS files. What is the best way to bundle all of these files together? Most sources online suggest using BundleConfig for bundling JS files, but I am working with an empty web application template in AS ...

Encountering the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" while using Django and Vue on my website

While working on my project that combines Vue and Django, I encountered a persistent error message when running the code: "Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yel ...

What is the best way to showcase a photo selected using an HTML input within a div container?

My goal is to select a photo from a folder and display it on a webpage, but I have struggled to find a working solution. Can this be achieved using just basic HTML, CSS, and JS? I am new to web development, so please forgive me for any beginner questions. ...

Error in VUE when attempting to splice the final element

This component is a simplified version of a larger component I'm currently working on. Can you help me solve the mystery - why am I encountering an error when trying to delete the last item from the list? The error only occurs when deleting the last ...

Using lazy loading and $ocLazyLoad for improved performance

Recently, I stumbled upon the $ocLazyLoad third-party Angular module that allows for the lazy loading of JavaScript files. This concept has me a bit perplexed. Can you explain the difference between lazy loading and caching, and why one would choose to l ...