Created
October 2, 2018 16:48
-
-
Save zwacky/298e540a453f5735c5481fa2f3c566e9 to your computer and use it in GitHub Desktop.
Vue directive like :class="{ 'css-class': isTrue }" that works with Ionic 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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