Created
December 3, 2021 06:33
-
-
Save wangziling/283ac6d60d11ee07777155121c078b0f to your computer and use it in GitHub Desktop.
Vue component for using v-if or v-show.
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
/* 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