javascript Vue.js:如果值为空,则不渲染属性(例如:to="" 或 type="")
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49848849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue.js: Don't render attributes if value is empty (e.g.: to="" or type="")
提问by Merc
I have Button component which renders a nuxt-link or a button depending if you provide some attribute like toor type.
我有一个 Button 组件,它呈现一个 nuxt-link 或一个按钮,具体取决于您是否提供了一些属性,如to或type。
<div class="Btn">
<component
:class="['Btn__button', createAppearanceClasses]"
v-on:click="click"
:disabled="disabled"
:is="type"
:to="to"
:href="external ? to : false"
:target="target"
:type="buttonType"
>
<slot />
</component>
</div>
(Whereas the typeis a computed property to return a nuxt-linkfor internal links, a atag if it is an external link or a buttonif these properties are not defined)
(而type是nuxt-link为内部链接返回 a 的计算属性,a如果是外部链接,则为标记,如果button未定义这些属性,则为a )
Now we sometimes render some Buttons which open a Modal or submit. There we don't pass any type or to attribute:
现在我们有时会渲染一些打开模态或提交的按钮。在那里我们不传递任何类型或属性:
<Btn :class="'FlexContent__button'"
:appearance="['rounded-corners']"
v-on:click.native="openOverlay"
>
{{ component.text }}
</Btn>
In the rendered HTML I get:
在呈现的 HTML 中,我得到:
<button disabled to="" target="" type="" class="Btn__button Btn__button--rounded-corners">
<button disabled to="" target="" type="" class="Btn__button Btn__button--rounded-corners">
If I validate this I get errors concerning these empty attributes:
Attribute to not allowed on element button at this point.
如果我验证这一点,我会收到有关这些空属性的错误:
Attribute to not allowed on element button at this point.
How can I render the attribute to=""only if I have an actual value passed to the Btn component?
to=""仅当我将实际值传递给 Btn 组件时,如何呈现属性?
I was thinking about something like this, but this does not work:
(to ? ':to="to"' : '')So I need some other solution for this.
我正在考虑这样的事情,但这不起作用:
(to ? ':to="to"' : '')所以我需要其他一些解决方案。
Thanks in advance for hints.
提前感谢您的提示。
cheers
干杯
采纳答案by DigitalDrifter
Any attribute that is bound using v-bindto a value that is null, undefined, or false will not be rendered in the element.
任何绑定v-bind到 null、undefined 或 false 值的属性都不会在元素中呈现。

