Javascript 如何根据Vue中的特定值使输入只读?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48764052/
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
How to make input read only based on particular value in Vue?
提问by Neha
How to make an input field read only based on Vue data?
如何根据Vue数据使输入字段只读?
For example:
例如:
<select class="form-control"
id="selectCategory"
:disabled="cat_id >=
1"
name="cat_id">
I want to make the field read only but not disabled. How can I achieve this?
我想让该字段只读但不禁用。我怎样才能做到这一点?
回答by P3trur0
Please note that, according to HTML specs, the select tag in HTML doesn't have a readonly attribute.
请注意,根据 HTML 规范,HTML 中的 select 标签没有 readonly 属性。
However, in general case, I'd go with something like this:
但是,在一般情况下,我会采用以下方法:
<input class="form-control" id="selectCategory" :readonly="cat_id >= 1">
Basically, the documentation says that if an attribute value evaluates to false, then the attribute being omitted. See herefor further details.
基本上,文档说,如果属性值计算为 false,则该属性被省略。请参阅此处了解更多详情。
回答by John Rajan
You can do something like this:
你可以这样做:
<input v-bind:readonly="isReadOnly">
回答by MyEmpireOfDuctTape
I ran into this issue while making a form for a password changing form and I encountered the browser trying to autocomplete everything. This should prevent the autocomplete from firing and also provide a method to change the value to suit your needs.
For some reason adding a v-bind:readonly property of true reverts to readonly="readonly"
Here is my currently working example which removes and re-adds the readonly property on focusout.
我在制作密码更改表单时遇到了这个问题,我遇到了浏览器试图自动完成所有内容。这应该可以防止自动完成触发,并提供一种方法来更改值以满足您的需要。
出于某种原因,添加一个 v-bind:readonly 的 true 属性会恢复为 readonly="readonly"
这是我当前工作的示例,它删除并重新添加了焦点上的 readonly 属性。
Vue Template HTML
Vue 模板 HTML
<input type="password" v-model="user.password" placeholder="Password" @focusin="toggleReadonly" @focusout="toggleReadonly" :readonly="true">
Method
方法
toggleReadonly(event){
event.preventDefault()
if(event.target.getAttribute('readonly') == 'readonly'){
event.target.removeAttribute('readonly')
}
else{
event.target.setAttribute('readonly', 'readonly')
}
}
回答by Suresh Velusamy
you could have a computed property that returns a boolean dependent on whatever criteria you need.
你可以有一个计算属性,它根据你需要的任何条件返回一个布尔值。
<input type="text" :disabled=isDisabled>
then put your logic in a computed property...
然后把你的逻辑放在一个计算属性中......
computed: {
isDisabled() {
// evaluate whatever you need to determine disabled here...
return true;
}
}

