v-if 在组件模板标签上 [英] v-if on a component template tag
问题描述
来自 文档:
<块引用>因为 v-if 是一个指令,所以它必须附加到单个元素.但是如果我们想要切换多个元素呢?在这在这种情况下,我们可以在元素上使用 v-if,它用作隐形包装.最终渲染结果将不包括元素.
但是在我的组件中的模板上:
<div>....
</模板>
但组件仍然呈现.
我问是因为我想在组件上添加一个钩子,所以如果 v-if 为真,我可以在 beforeMounted
和 beforeDestroyed
中执行一些代码,如果为假.
如果我不明白你在做什么...
您将 v-if 放入 .vue
文件中的模板标签,对吗?像这样
//component.vue<模板 v-if="false"><div>我的组件
</模板><脚本>导出默认{名称:'我的组件'};<样式></样式>
对吗?
如果是,那么你做错了.
模板中有一个标签供Webpack Vue Loader 加载组件模板.
所以 if
必须放在模板标签中.
//component.vue<模板><div v-if="false">我的组件
</模板><脚本>导出默认{名称:'我的组件'};<样式></样式>
如果需要隐藏"多个元素,只需封装成另一个div
即可.
From the docs:
Because v-if is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use v-if on a element, which serves as an invisible wrapper. The final rendered result will not include the element.
But on my template in my component:
<template v-if="false">
<div>
....
</div>
</template>
But the component still renders.
I ask because I want a hook on the component so if v-if is true, I can do some code in beforeMounted
and beforeDestroyed
if false.
If I undestood what are you doing...
You're putting v-if int the template tag ina .vue
file right?
Like this
// component.vue
<template v-if="false">
<div>
My Component
</div>
</template>
<script>
export default {
name: 'my-component'
};
</script>
<styles>
</styles>
Right?
If YES, you are doing it wrong.
The template there is a tag for Webpack Vue Loader to load the component template.
So the if
must go inside the template tag.
// component.vue
<template>
<div v-if="false">
My Component
</div>
</template>
<script>
export default {
name: 'my-component'
};
</script>
<styles>
</styles>
If you need to "hide" multiple elements, just encapsulate into another div
.
这篇关于v-if 在组件模板标签上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!