gpt4 book ai didi

vue.js - 自定义 Vue 指令省略标签但呈现标签的内容?

转载 作者:搜寻专家 更新时间:2023-10-30 22:19:50 25 4
gpt4 key购买 nike

我想创建一个自定义 Vue 指令来省略标签,但在指令为真时呈现标签的内容。

例如,如果我的 vue 实例的数据定义为

 data:{
omitIt: true
}

如果标记看起来像这样:

 <div v-omit="omitIt" class="someClass">
Hello world!
</div>

omitIt 如上所示设置为 false 时,我希望将以下内容呈现到 dom 中:

<div class="someClass">
Hello world!
</div>

但是当 omitIt 为真时,我只想将以下内容呈现到 dom 中:

Hello world!

我最初尝试通过执行以下操作(诚然不是自定义 vue 指令)来解决此问题:

 <template v-if="!omitIt">
<div class="someClass">
</template>
Hello world!
<template v-if="!omitIt">
</div>
</template>

上面的内容并不漂亮,但我认为它可能会起作用。但是当 omitIt 为 false 时渲染到 dom 中的内容是:

 <div class="someClass"></div>
Hello world!

关于如何实现我正在寻找的结果有什么建议吗?

最佳答案

我认为@Nit 的回答很好而且简单,并赞成它,但它确实有一个缺陷:插槽可能不是根元素,因此当需要省略包装器时组件将失败。这是因为插槽可以包含多个元素,如果插槽确实包含多个元素,则最终可能会有多个根元素,这是不允许的。

我有一个部分解决方案,如果组件换行,它只呈现插槽中的第一个元素。

Vue.component("wrapper", {
props:{
nowrap: {type: Boolean, default: false}
},
render(h){
// This will *only* render the *first* element contained in
// the default slot if `nowrap` is set. This is because a component
// *must* have a single root element
if (this.nowrap) return this.$slots.default[0]
// Otherwise, wrap the contents in a DIV and render the contents
return h('div', this.$slots.default)
}
})

这是它工作的一个例子。

console.clear()

Vue.component("wrapper", {
props:{
nowrap: {type: Boolean, default: false}
},
render(h){
// Log a warning if content is being omitted
const omissionMessage = "Wrapper component contains more than one root node with nowrap specified. Only the first node will be rendered."
if (this.$slots.default.length > 1 && this.nowrap)
console.warn(omissionMessage)

// This will *only* render the *first* element contained in
// the default slot if `nowrap` is set. This is because a component
// *must* have a single root element
if (this.nowrap) return this.$slots.default[0]

// Otherwise, wrap the contents in a DIV and render the contents
return h('div', this.$slots.default)
}
})

new Vue({
el: "#app"
})
.someClass{
color: blue
}
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
<wrapper class="someClass">Hello World</wrapper>
<wrapper nowrap>No wrap, single root</wrapper> <br>
<wrapper nowrap>
No wrap, two roots. Paragraph is ommitted.
<p>Some other content</p>
</wrapper>
</div>

一些注意事项:除非您将 nowrap 添加为属性,否则该组件将始终换行。另外,请注意该类已添加到包装容器中,但未将其指定为 Prop 。这是因为 Vue 会自动渲染组件根元素上未指定为 props 的属性,除非您告诉它不要这样做。

关于vue.js - 自定义 Vue 指令省略标签但呈现标签的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201768/

25 4 0