简体   繁体   中英

VueJS re-render component after EventBus receives new data

The computed function is called every time an event bus receives new data. How can I re-render the component, so that the new data are displayed?

<template lang="pug">
  div
    div(v-for='user in filtered')
      p {{ user.name }}
</template>

<script>
  computed: {
    filtered() {
      // filter by using data
      return this.users.filter((user) =>
        return this.data.includes(user.name)
      );
    }
  },
  created() {
    EventBus.$on('data', (data) => {
      this.data = data;
    }
  },
  data() {
    return {
      data: [],
      users: [
        // users
      ]
    }
  }
</script>

To detect if a rendering is needed, Vue checks references of objects and arrays , not their values nor their properties.

I suspect the data array passed from the event bus to be the same as the one in the component.

Use the spread operator to create a new array and trigger a re-render:

created() {
  EventBus.$on('data', (data) => {
    this.data = [...data];
  }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM