VueJS 有条件地为元素添加属性 [英] VueJS conditionally add an attribute for an element

查看:53
本文介绍了VueJS 有条件地为元素添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VueJS 中,我们可以使用 v-if 添加或删除 DOM 元素:

In VueJS we can add or remove a DOM element using v-if:

<button v-if="isRequired">Important Button</button>

但是有没有办法添加/删除 dom 元素的属性,例如有条件地设置所需的属性:

but is there a way to add / remove attributes of a dom element eg for the following conditionally set the required attribute:

Username: <input type="text" name="username" required>

类似于:

Username: <input type="text" name="username" v-if="name.required" required>

有什么想法吗?

推荐答案

尝试:

<input :required="test ? true : false">

更新:它在 Vue 3 中发生了变化,请参阅此答案 https://stackoverflow.com/a/64598898

这篇关于VueJS 有条件地为元素添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆