Skip to content

Instantly share code, notes, and snippets.

@zwacky
Created October 2, 2018 16:48
Show Gist options
  • Save zwacky/298e540a453f5735c5481fa2f3c566e9 to your computer and use it in GitHub Desktop.
Save zwacky/298e540a453f5735c5481fa2f3c566e9 to your computer and use it in GitHub Desktop.
Vue directive like :class="{ 'css-class': isTrue }" that works with Ionic 4
/**
* usage:
*
* <AnyComponent v-toggleClass="{ 'any-component--active': isActive }"></AnyComponent>
*/
// toggleClass.directive.ts
import { DirectiveOptions } from 'vue';
function toggle(el, classKeys: {[key: string]: boolean}) {
const toAdd = Object.keys(classKeys)
.filter(key => classKeys[key]);
const toRemove = Object.keys(classKeys)
.filter(key => !classKeys[key]);
el.className = el.className.split(' ')
.filter(name => toAdd.indexOf(name) === -1)
.concat(toAdd)
.filter(name => toRemove.indexOf(name) === -1)
.join(' ');
}
const toggleClass: DirectiveOptions = {
bind: (el, node) => toggle(el, node.value),
update: (el, node) => toggle(el, node.value),
};
export default toggleClass;
// AnyComponent.vue
<script lang="ts">
import toggleClass from '…/toggleClass.directive';
@Component({
directives: { toggleClass }
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment