Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Created February 7, 2018 17:36
Show Gist options
  • Save rodneyrehm/6f862356e05a7cf27c3a43714c2b655e to your computer and use it in GitHub Desktop.
Save rodneyrehm/6f862356e05a7cf27c3a43714c2b655e to your computer and use it in GitHub Desktop.

How best to encapsulate data retrieval and conversion stuff as shown in the gustav.mixin.js demo, so that it can be easily used in multiple components like gustav.vue?

The problem here is that from the component's perspective we're only interested in providing ottoId and receiving gustav. All other properties from data, computed, methods are at best irrelevant to the component - at worst may cause conflicts.

Is there any sane way I can stay in the "how a mixin would do it" kind of code, but achieve only the export of computed.gustav, watch.ottoId and created?

import { mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
gustavIndex: 'gustav/index',
ottoIndex: 'otto/index',
}),
// INPUT: overwritten by the component using this mixin
ottoId () {
return null
},
// OUTPUT: consumed by the component using this mixin
gustav () {
return this.gustavIndex[this.gustavId]
},
// mixin internal stuff the component should not be polluted with
gustavId () {
const otto = this.ottoIndex[this.ottoId]
return otto && otto.gustavId
},
},
// mixin internal stuff the component should not be polluted with
methods: {
...mapActions({
loadGustav: 'gustav/load',
loadOtto: 'otto/load',
}),
load () {
this.loadGustav()
this.loadOtto(this.ottoId)
},
},
// mixin internal stuff the component should not be polluted with
watch: {
ottoId () {
this.load()
},
},
// mixin internal stuff the component should not be polluted with
created () {
this.load()
},
}
<template>
<div v-if="gustav">{{ gustav.name }}</div>
</template>
<script>
import GustavMixin from './gustav.mixin'
export default {
mixins: [ GustavMixin ],
props: {
ottoId: {
type: String,
required: true
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment