Changes in VueJS parent data do not automatically trigger updates in child components

Within my application architecture, I have a primary component that encapsulates several subordinate components. The objective is for the main component to manage the state of all its child components. Whenever a child component is clicked, it should notify the parent component so that all siblings can be updated accordingly.

JSFIDDLE DEMO

Vue.component('child', {
  template: '#childtemplate',
  props: ['index', 'activeIndex'],
  methods: {
    updateActiveIndex: function() {
      console.log("emitting");
      this.$emit('updateEvent', this.index);
    }
  }
});

Vue.component('parent', {
  data: function() {
    return {
      activeIndex: 0
    }
  },
  render: function(createElement) {
    console.log("rendering ai->", this.activeIndex);

    this.$options._renderChildren.forEach(function(item, index) {
      if (item.data === undefined)
      return;

      item.componentOptions.propsData = {
        index: index,
        activeIndex: this.activeIndex
      }
    }.bind(this));

    return createElement('div', {}, this.$options._renderChildren);
  },
  methods: {
    handleToggle: function(index) {
      this.activeIndex = index;
    }
  },
  created: function() {
    this.$on('updateEvent', this.handleToggle);
    
    setTimeout(function(){this.activeIndex = 6}.bind(this), 3000);
  }
});

new Vue({
  el: '#app'
})

I've explored different strategies such as adding event listeners to the `createElement` function in the `parent` component's `render()` method and setting an `$on` listener in the `created` lifecycle hook of the `parent`. However, these attempts were unsuccessful.

To work around this issue, I devised a temporary solution by directly referencing a `$parent` callback from the child component, passing an index value upwards. This approach triggers vue warn errors but accomplishes the task at hand.

Is there a more elegant solution available?

Answer №1

Not entirely convinced this method is an improvement, but it does function as intended in this revised code snippet. Essentially, the process involves looping through the default slot, filtering out any elements that are not tagged as child, then applying the necessary attributes and incorporating the content of each child's slot.

render: function(createElement) {
  console.log("rendering ai->", this.activeIndex);

  const children = [];
  for (let i=0; i < this.$slots.default.length; i++){
    if (!(this.$slots.default[i].tag == "child"))
      continue;

    children.push(createElement(Child, {
      props:{
        index: i,
        activeIndex: this.activeIndex
      },
      on:{
        updateEvent: this.handleToggle
      }
    }, this.$slots.default[i].children))

  }

  return createElement('div', {}, children);
}

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

Ways to alter an array of objects without using a loop

The following code is functioning properly: for(let i=0;i< this.Array.length ; i++){ if(this.Array[i].propertyObject.hasOwnProperty('header')) this.Array[i].ColumnName = this.Array[i].propertyObject.header; } I am int ...

Sending an array of JSON data from PHP to JavaScript

After exploring various solutions on how to get JSON in JavaScript from a PHP array, I am still encountering an error. My myfile.php file includes: <?php ................ print json_encode($data, JSON_NUMERIC_CHECK); mysql_close($con); ?> <html&g ...

Is being unfazed by work a common occurrence?

After completing a complex cycle that processes data from the database and writes it to an array, I encounter a situation where the array processing function is triggered before the array is fully populated. This forces me to use setTimeout() for proper ti ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Sweetalert continues to delete items despite selecting "NO" option

While working on a Laravel project, I decided to practice CRUD operations using AJAX. In one of my tasks, I wanted to display a confirmation message using SweetAlert before deleting a field from the database. The SWAL alertbox had a message that said "Do ...

Error message: Cannot access 'context' property in Webpack 4 css modules due to TypeError

I recently updated to webpack 4 and I am utilizing css modules. Encountered ERROR: ERROR in ./client/src/common/accordian-component/accordian.css (./node_modules/css-loader??ref--5-1!./node_modules/postcss-loader/lib??ref--5-2!./client/src/common/acc ...

I am unable to save the data received from the payment API

I've been working on developing an e-commerce system, but I'm facing an issue with the iyzipay payment API. Although I successfully make a request and receive a response from the server, I'm unable to store the data that comes back. Can anyo ...

Employing ng-click within a displayed column of Datatable

Currently, I am utilizing a plain Datatable in AngularJS without any Angular-Datatable libraries. Everything appears to be working well except for one issue. Here is the datatable code snippet: $scope.siInfoTable = $('#siInfoTable').DataTable({ ...

Implement various actions when the window is resized

The carousel code I have found returns a different number of items to display based on screen size. You can check it out here. $(function() { var mini = 1000; var big = 1280; if (window.screen.availWidth < mini) { $('#carousel1').jsCar ...

How can we delete a specific word from a string if it is found in an

Facing a seemingly simple problem that's proving tricky to solve. I have an array of product names and a sentence. The goal is to remove any product names from the sentence if they appear in it. const products = ["premium t-shirt", "t-shirt", "swea ...

Converting Boolean Values to Strings in Ionic/Angular NGX Datatable

Currently, I am working on a project to develop an Ionic/Angular application. For this application, I am utilizing NGX datatable which is functioning well. However, I have a specific requirement - I need to display boolean values in German instead of Engli ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Ways to enable users to add or modify spry widgets

Is there a way to make it easier for users to edit spry accordions/tabbed panels in a navigation tool for locating points in PDFs? The PDFs are updated regularly, so the navigation will need frequent updates. The users who will be maintaining this tool h ...

Guide to creating dynamic borders around your PHPexcel output

Looking for assistance on adding borders around output arrays in an Excel report using PHPexcel. I reviewed the documentation, but the examples are static, requiring a predefined number to set. My goal is to have all arrays transferred to Excel with bord ...

Unable to receive data in an array with Vuejs

Here is the code snippet I am working with: let data = res.data.data; console.log('data: ', data) const list = []; for(let i = 0; i < data.length; i++){ console.log('data i: ', data[i]) //this line is not being printed in the ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

Learn the process of transferring data from a page to a layout in NUXT

I am in the process of creating a basic website. The goal is to dynamically change the Navbar elements based on the data set in the navLayout within the page template. My plan is to pass this data to the layout and then utilize props to transmit it to the ...

React: Encountered an expression in JSX where an assignment or function call was expected

Trying to build a left-hand menu for my test application using react. Encountering a compilation error in the JSX of one of my classes. Is it because HTML elements cannot be placed within {} scripts in JSX? If so, how do I fix this? ./src/components/Left ...

Having trouble getting Vue JS 2.0 to display content?

When working with Vue (^2.0.0-rc.6) and Browserify, the entry point is index.js: import Vue from 'vue' import App from './containers/App.vue' new Vue({ // eslint-disable-line no-new el: '#root', render: (h) => h(App) ...

What is the appropriate way to utilize `render_template` from Flask within Angular?

I'm facing an issue where I need to implement different routes for various Angular Material tabs. I have attempted to directly call Flask from the template, as demonstrated below, but unfortunately, I am unable to invoke render_template from Angular. ...