Reputation: 3918
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.
Upvotes: 0
Views: 384
Reputation: 22403
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
Upvotes: 1
Reputation: 8716
This is a bad approach anyways. Store should be used to contain the data and components should just "show" it and manipulate it through actions and mutations.
So in this case, I'd remove the props
, created
and data
part and add a getter
to the store which should be implemented in a computed
in the component. Nothing fancy here.
You shouldn't need to manually load the data with a proper store setup. Always make a getter and "load" it into the component with a computed
.
Upvotes: 0