有条件地呈现指令



我一整天都在努力寻找一种方法来有条件地渲染元素上的指令。我结束了这个页面:https://vuejs.org/guide/extras/render-function.html,但后来我不能追加我的编译模板(使用vue-template-compiler,因为我使用的vue的一些版本不包括编译器)。

在一天结束的时候,这是我的想法:

<div>Some foo</div>
<template v-if="withDirective">
<input :value="value"
:disabled="disabled"
:type="type"
v-some-directive="someValue" />
</template>
<template v-else>
<input :value="value"
:disabled="disabled" 
:type="type" />
</template>
<div>Some bar</div>

有更好的方法吗?我在输入上有很多属性,所以有很多重复的代码,我想要避免。这个html是在自定义组件中,所以所有的值,比如disabled, required等,都是从外部传入的props。

到目前为止,我发现最好的方法是有条件地使用compileToFunctions编译字符串模板。因此,在模板中没有template标签和v-if,我只是在编译组件之前添加了条件指令。

注意

请记住,编译是运行时的,我没有足够的Vue经验来判断这种方式是否比使用v-if更快。可以肯定的是,我们在模板中保存了许多重复的行,这在编辑公共部分时很方便。

最新更新