我找到了两种方法来实现您想要实现的目标,第一种是在 v-else 中重复子代码(不是最佳选择,因为您需要重复代码..,但您可以将内容包装在组件中) :
<div v-if="showparent" class="parent">
<div class="child">
Child should always be visible
</div>
</div>
<div v-else class="child">
Child should always be visible
</div>
或者您可以创建自定义组件:
Vue 2 使用渲染函数
export default {
name: "v-if-parent",
props: {
condition: {
type: Boolean,
required: true
},
fallbackWrap: {
type: String,
default: 'div'
}
},
render(el) {
if (this.condition) {
let parent = this.$scopedSlots.parent()[0];
if (typeof this.$scopedSlots.default === 'function')
parent.children = this.$scopedSlots.default();
return parent;
} else if (typeof this.$scopedSlots.default === 'function') {
let children = this.$scopedSlots.default();
if (children.length > 1) {
//We can only return a single vnode in vue 2 so if multiple children, wrap them in a div
return el(this.fallbackWrap, null, children)
}
return children[0];
}
return null;
}
}
Usage
<v-if-parent :condition="showparent" fallback-wrap="span">
<template #parent><a href="somelink" /></template>
This text is always visible <span>You can include absolutely whatever you want in the default slot</span>
</v-if-parent>
使用 Teleport 的 Vue 3
<template>
<slot v-if="condition" name="parent" :ref="(el) => (telRef = el)"
><slot></slot
></slot>
<Teleport v-if="condition && telRef" :to="telRef"><slot></slot></Teleport>
<slot v-else></slot>
</template>
<script setup>
import { ref } from "vue";
defineProps({
condition: {
type: Boolean,
required: true,
},
});
const telRef = ref(null);
</script>
Usage
<v-if-parent :condition="showparent" fallback-wrap="span">
<template #parent="{ref}"><a href="somelink" :ref="ref" /></template>
This text is always visible <span>You can include absolutely whatever you want in the default slot</span>
</v-if-parent>