The event bus in Vue.js is failing to emit events and send data to the component

Trying out the Vue event bus for the first time to pass data to child components from the main vue instance. However, despite my testing, I can't seem to retrieve the data inside my components. I believe the code is correct, but I'm uncertain. Is there a mistake in the code? I am working on a WordPress theme and have three separate files (not using webpack). Two JavaScript files will contain the main Vue instance and the components, while another file will hold the template itself. Any assistance would be greatly appreciated.

// app.js file
Vue.prototype.$eventHub = new Vue(); // Global event bus

Vue.directive('prlx', VuePrlx.VuePrlxDirective);

new Vue({
  el: '#ume',
  router,
  data: {
    pageData: [],
    feedImg: []
  },
  watch: {
    $route( to, from ){
      console.log('main instance:'+ to, from);
      this.getPage();
    }
  },
  methods: {
    getPage: function(){
      //console.log(this.$route);
      var slug = this.$route.fullPath.replace(/\//g, "")
      axios.get(uptheme.pages_rest_url+'?slug='+ slug)
        .then( (response) => {
        console.log(response.data);
        response.data.forEach( (item, i) => {
          this.pageData = [item];
          if( item.embedded.gallery_images ){
            item.embedded.gallery_images.forEach( (img) => {
              this.feedImg.push(img);
            });
          }
        });
      });
      this.$eventHub.$emit('page_data', this.pageData);
    },
  }
});

components.js file:

Vue.component('ume-about',{
  template: '#about-tpl',
  data() {
    return {
      pageData: [],
      feedImg: []
    }
  },
  created() {
    this.$eventHub.$on('page_data', (data) => {
      console.log(data);
      this.pageData.push(data);
    });
  },
  beforeDestroy() {
    $eventHub.$off('page_data');
  }
});

about-template.php file

// This file holds the template only
<script type="text/x-template" id="about-tpl">
  <div class="container-fluid p-0">
<!-- page cover -->
    <div class="row m-0" v-for="page in pageData">
      <div class="col-sm-12 col-md-12 col-lg-12 col-pagecover p-0" v-if="page.embedded.first_featured_image">
        <img class="img-fluid w-100 h-100 position-absolute" :src="page.embedded.first_featured_image">
        <h1 class="text-white position-relative mt-5 pl-5 pt-5" style="z-index:2;" >{{ page.title.rendered }}</h1>
        <h4 class="text-white position-relative pl-5" style="z-index:2;" v-if="page.ucm._page_subtitle[0]">{{ page.ucm._page_subtitle[0] }}</h4>
      </div>
        <div class="overlay position-absolute"></div>
    </div>
<!-- main content -->
    <div class="row m-0" v-for="page in pageData">
      <div class="col-sm-12 col-md-6 col-lg-6 mt-md-5 mb-md-5 p-5">
        <p class="" v-html="page.content.rendered"></p>
      </div>
      <div class="col-sm-12 col-md-6 col-lg-6 mt-md-5 mb-md-5 p-0">
        <img class="img-fluid w-100" :src="page.embedded.second_featured_image">  
      </div>
    </div>
<!-- parallax -->
    <uptheme-parallax v-for="(page, idx) in pageData" :url="page.embedded.parallax_image" :message="page.excerpt.rendered" ></uptheme-parallax>
<!-- swiper slider -->
    <uptheme-swiper :feed-img="feedImg"></uptheme-swiper>
<!-- column 1 -->
    <div class="row m-0" v-for="page in pageData">
      <div class="col-sm-12 col-md-6 col-lg-6 p-0 mt-md-5 mb-md-5" v-if="page.embedded.col_1_image">
        <img class="img-fluid w-1...

Answer №1

Make sure to include this.$eventHub.$emit('page_data', this.pageData); inside your axios function, otherwise it will not return any data.

axios.get(uptheme.pages_rest_url+'?slug='+ slug)
    .then( (response) => {
        console.log(response.data);
        response.data.forEach( (item, i) => {
          this.pageData = [item];
          if( item.embedded.gallery_images ){
            item.embedded.gallery_images.forEach( (img) => {
              this.feedImg.push(img);
            });
          }
        });

        this.$eventHub.$emit('page_data', this.pageData);
    });

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

Generating and saving a PDF file using a binary string in JavaScript or TypeScript

A server response to an Axios request contains the content of a PDF as a binary string. export const fetchPDFfile = async (id: string): Promise<string> => { const { data } = await http.get<string>(`${baseUrl}/${id}.pdf`); return data; } ...

What is the best way to incorporate data from JSON objects in nested arrays within an array into HTML using AngularJS?

I have been struggling to display the JSON data in list.html in the desired format. Despite trying different approaches from similar posts, I have not been successful as my JSON structure is unique. How can I ensure that fields such as givenName, familyNam ...

Converts date format from RSS feed to the "time.ago" format

I am currently working on creating an RSS feed webpage and RSS answer which includes a date formatted as "Thu, 15 Aug 2013 12:42:05 -0700". I would like to change this format to something like "12 minutes ago". I have attempted using , however it does no ...

Issue with loading dynamic content on a webpage using HTML and JavaScript through AJAX

I am currently using the jQuery UI Tabs plugin to dynamically load HTML pages through AJAX. Here is the structure of the HTML code: <div id="tabs"> <ul> <li><a href="pageWithGallery.html" title="pageWithGallery">Gallery< ...

Using AJAX and jQuery on a PHP site that has been returned may cause compatibility issues

Here is the issue I am facing: I created a webpage using divs. When a link is clicked, I use a XMLHttpRequest function in JavaScript to fill a div with the output of a PHP file (MySQL Queries). However, when I try to enable/disable buttons and textareas us ...

What is the best way to differentiate the behavior of two identical classes using a single JavaScript function?

Can someone help me figure out how to make two circles move differently with the same JavaScript function? I'm new to JavaScript and struggling to differentiate between classes in HTML to achieve this. My goal is to have each circle move randomly and ...

Dealing with multiple JSON objects and organizing them into an array

After making an ajax call, I receive a response consisting of multiple JSON objects. // Sample response from ajax call: {"name":"suresh","class":"10th"},{"name":"suresh","class":"10th"} I am looking for assistance in splitting these objects and storing t ...

Adjust the color as you scroll

It appears that the example provided changes the color from red to blue from the bottom, but I am looking for a solution that will change the color from top as I scroll. Can anyone help me achieve this effect using JavaScript? Here is another great referen ...

Tips for implementing focusout on multiple elements while avoiding it when switching focus between them

Looking to create a searchable input that displays a dropdown of possible values on focusin, populated by server-side language. Attempted using focusin on elements not involved with the following code: $("body").not($(".dropdownSearch") ...

Encountering difficulties in accessing state while utilizing async callback functions in React.js

After finding this function on Stack Overflow, I decided to use it in order to update a database and profile information immediately after a user signs up. The function is working as expected, but I am encountering an issue where I can no longer access the ...

Encountering a Laravel error related to "SymfonyComponentHttpKernelExceptionHttpException"

After transferring my Laravel and Vue JS application to our server, I encountered an error that reads: Symfony\Component\HttpKernel\Exception\HttpException A similar issue was reported here, but unfortunately no solution was provid ...

Stop unauthorized HTTP requests by limiting a web application to only communicate with specified domains

I have come up with an innovative security feature idea for browsers/web clients, but I have not been able to find any information or discussions about it. Therefore, I am seeking an answer to determine the feasibility and necessity of such a feature. Que ...

How can access to web pages be limited to only logged-in users using Node.js?

Currently, I am attempting to create a filter using tokens in order to limit access to certain pages for unauthenticated users on node.js 0.10. I have implemented a middleware as shown below: app.all( "/product/*" , handler); // will not match /product ...

When I click on something else, the dropdown doesn't automatically close

In my current setup, I have 3 dropdowns on the page. When I click outside of any dropdown, they are correctly closed. However, if one dropdown is already open and I click on another one, the previously opened dropdown remains open. I want all dropdowns to ...

Enhance tvOS connectivity with React Native's caching networking library

Is there a networking library that is suitable for react-native and comes with local cache capabilities? I am keen on implementing this feature using an efficient architecture, including my Model, Stores, and APIService within the app. ...

What causes an "Undefined index" error in jQuery when making AJAX requests?

Whenever I make an AJAX request in my main.js file, I encounter the following error message: Undefined index: id in sqlinfo.php on line 13 I am puzzled because I believe that I am populating the request object correctly. What's even more perplexing i ...

Utilize ng-change directive within an AngularJS loop

I am facing a particular issue with my Angular JS directive that is designed to verify whether an input is a number or not. If the input is not a number, then it needs to be corrected. Here is the code for my directive: app.directive('numberValidate& ...

The Comet approach (utilizing long polling) and the status of XmlHttpRequest

Recently, I decided to explore raw XmlHttpRequestObjects along with Comet Long Polling. While typically I would rely on GWT or another framework for this task, I wanted to expand my knowledge in the area. Here's a snippet of the code I wrote: functi ...

Angular 2: Dynamic URLs for Templates

I am trying to switch between two different sidebars based on a variable obtained from the URL. However, when I attempt to implement this feature, I encounter an error message. @Component({ selector: 'sidebar', templateUrl: './sideb ...

Is there a way to transfer the value of an angular 2 variable to a javascript function?

image description goes here Check out this picture I have. I am trying to pass the values of "c.name" and "c.image_Url" in an onclick function, as shown in the image. ...