Skip to content

Instantly share code, notes, and snippets.

@wangziling
Created December 3, 2021 06:33
Show Gist options
  • Save wangziling/283ac6d60d11ee07777155121c078b0f to your computer and use it in GitHub Desktop.
Save wangziling/283ac6d60d11ee07777155121c078b0f to your computer and use it in GitHub Desktop.
Vue component for using v-if or v-show.
/* eslint-disable no-unused-vars */
import { Component, Prop, Vue } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import _ from 'lodash';
@Component
export default class VIfOrShow extends Vue {
/* Data START */
/* Data END */
/* Prop START */
@Prop({
type: Boolean,
required: false,
default: false
})
useVShow!: boolean;
@Prop({
type: Boolean,
required: true,
default: false
})
status!: boolean;
/* Prop END */
/* Methods START */
/* Methods END */
/* LifeCycle START */
render (h: CreateElement) {
const slotsDefault = this.$slots.default;
if (!Array.isArray(slotsDefault)) {
return slotsDefault;
}
if (this.useVShow) {
slotsDefault.forEach(vNode => {
if (!vNode) {
return;
}
let vNodeData = _.get(vNode, 'data');
if (!vNodeData) {
this.$set(vNode, 'data', vNodeData = {});
}
const vNodeDirectives = _.get(vNodeData, 'directives');
const directive = {
name: 'show', // v-show is a real directive, but v-if not.
value: this.status
};
if (!(Array.isArray(vNodeDirectives))) {
this.$set(vNodeData, 'directives', [directive]);
return;
}
vNodeDirectives.push(directive);
});
return slotsDefault;
}
return this.status ? slotsDefault : null;
}
/* LifeCycle END */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment