Skip to content

Instantly share code, notes, and snippets.

@danielsdeboer
Last active November 29, 2017 16:41
Show Gist options
  • Save danielsdeboer/6736df0419ecb94831d3aecd2167f815 to your computer and use it in GitHub Desktop.
Save danielsdeboer/6736df0419ecb94831d3aecd2167f815 to your computer and use it in GitHub Desktop.
A VueJS mixin to automatically map class prop names and values to a computed value.
// The mixin
import kebabcase from 'lodash.kebabcase'
export default {
// The component will bind class to this computed property.
computed: {
classes () {
const classes = {}
Object.keys(this.$props)
.filter(name => name.includes('Class'))
.forEach(name => { classes[this.propToClass(name)] = this[name] })
return classes;
}
},
methods: {
// Convert the camelCase prop name to snake-case and remove the '-class' portion.
// This could run any transform you want, this is what my usecase needed.
propToClass (name) {
return kebabcase(name).replace('-class', '')
}
},
}
// An example component:
<template>
<div :class="classes">
<slot></slot>
</div>
</template>
<script>
import HtmlClassMixin from 'Mixins/HtmlClass'
export default {
props: {
hasTextCenteredClass: { type: Boolean }
},
mixins: [ HtmlClassMixin ]
}
</script>
// In another component:
<example-component :has-text-centered-class="true">
<p>Lorem Ipsum</p>
</example-component>
// Will render out as:
<div class="has-text-centered"><p>Lorem Ipsum</p></div>
// With the mixin you only ever have to define the props.
// You don't have to set up the prop and the computed property
// and make sure they're in sync.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment