在 Vue 3 中,如何有条件地包装元素,而不是使用
v-if
指令创建两个单独的块?
我这里有一个简化的示例,但问题涉及条件包装。这里有一些问题,在 html 块中,与脚本设置块中的状态有很多耦合,因此将其抽象到子组件会带来更多麻烦,而不是值得的。将会出现混合状态,并且必须处理从子级到父级的数据发送,这将是一团糟。其次,由于 html 块的大小,创建手动渲染函数也会很混乱。
下面的代码确实有效,但是有一个大块是重复的,因为我需要一个额外的包装器。请注意,这个问题不是关于如何使用 css 来解决这个问题。
<script setup>
const isMobile = ref(true)
</script>
<template>
<div v-if="isMobile" class="mobile-wrapper">
<div class="product-meta">
<!-- long html block tightly coupled with script setup block -->
</div>
</div>
<div v-else class="product-meta">
<!-- same html block -->
</div>
</template>
我们可以使用计算属性和模板槽的组合来实现元素的条件包装,而无需求助于重复的 HTML 块
<script setup>
const isMobile = ref(true);
const wrapperElement = computed(() =>
isMobile.value ? 'div class="mobile-wrapper"' : 'div'
);
</script>
在包装器元素上使用
v-slot
指令来定义将渲染包装内容的槽
代码片段
<template :tag="wrapperElement">
<div class="product-meta">
</div>
</template>