Search code examples
vue.jsvuejs2vuex

Mutiple Data Source for a component


I am in a process to support multiple data source to show data in a component via props & store.

The idea is to build a list component, which will load the data from the store if no props present. Otherwise, show the data from props. Thus, I am ensuring reusability in the context of search functionality and normal listing view.

Here is the code looks like,

<template>
  <div>
    <li v-for="user in this.dataSource" :key="user.age">
      {{ user.name }}
    </li>
  </div>
</template>
<script>
export default {
  props: {
    userData: {
      type: Array,
      default: null,
    }
  },
  created() {
    // dispatch action to get user data
    this.$store.dispatch("GET_USER_DATA");
  },
  data() {
    return {
      dataSource: this.userData !== null ? this.userData: this.$store.state.users
    };
  }
};

As of now, the store holds just static data. But in the context of REST it will be async in nature. So sometimes, I see no data.

So my question is that is this logic of dataSource can be improved further?

Thanks Robin.


Solution

  • You should change dataSource to computed property. It will automatically re-computed when this.userData is changed or this.$store.state.users is changed

    computed: {
      dataSource() {
        return this.userData !== null ? this.userData: this.$store.state.users
      }
    }
    

    For more information about computed in Vuejs, please check the document