Javascript 如何在 vue.js 中有条件地禁用输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38085180/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:04:31  来源:igfitidea点击:

How to disable input conditionally in vue.js

javascripthtmlformsvue.js

提问by Zaffar Saffee

I have an input:

我有一个输入:

<input type="text" id="name" class="form-control" name="name"  v-model="form.name" :disabled="validated ? '' : disabled">

and in my Vue.js component, I have:

在我的 Vue.js 组件中,我有:

..
..
ready() {
        this.form.name = this.store.name;
        this.form.validated = this.store.validated;
    },
..

validatedbeing a boolean, it can be either 0or 1, but no matter what value is stored in the database, my input is always disabled.

validated作为 a boolean,它可以是01,但无论数据库中存储什么值,我的输入总是被禁用。

I need the input to be disabled if false, otherwise it should be enabled and editable.

如果false,我需要禁用输入,否则它应该被启用和可编辑。

Update:

更新:

Doing this always enablesthe input (no matter I have 0 or 1 in the database):

这样做总是会启用输入(无论我在数据库中有 0 还是 1):

<input type="text" id="name" class="form-control" name="name"  v-model="form.name" :disabled="validated ? '' : disabled">

Doing this always disabledthe input (no matter I have 0 or 1 in the database):

这样做总是禁用输入(无论我在数据库中有 0 还是 1):

<input type="text" id="name" class="form-control" name="name"  v-model="form.name" :disabled="validated ? disabled : ''">

回答by asemahle

To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string 'false'.

要删除禁用的道具,您应该将其值设置为false。这需要是 的布尔值false,而不是字符串'false'

So, if the value for validatedis either a 1 or a 0, then conditionally set the disabledprop based off that value. E.g.:

因此,如果 for 的值validated是 1 或 0,则disabled根据该值有条件地设置prop。例如:

<input type="text" :disabled="validated == 1">

Here is an example.

这是一个例子。

var app = new Vue({
  el: '#app',

  data: {
    disabled: 0,
  },
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="disabled = (disabled + 1) % 2">Toggle Enable</button>
  <input type="text" :disabled="disabled == 1">
    
  <pre>{{ $data }}</pre>
</div>

回答by David Morrow

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 this.form.validated;
  }
}

回答by Sebastiao Marcos

Not difficult, check this.

不难,看看这个。

<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name"  v-model="form.name" :disabled="disabled">

jsfiddle

提琴手

回答by Francis Leigh

Your disabled attribute requires a boolean value:

您的 disabled 属性需要一个布尔值:

<input :disabled="validated" />

<input :disabled="validated" />

Notice how i've only checked if validated- This should work as 0 is falsey...e.g

注意我是如何只检查是否validated- 这应该像0 is falsey......例如

0 is considered to be false in JS (like undefined or null)

0 is considered to be false in JS (like undefined or null)

1 is in fact considered to be true

1 is in fact considered to be true

To be extra careful try: <input :disabled="!!validated" />

要格外小心,请尝试: <input :disabled="!!validated" />

This double negation turns the falseyor truthyvalue of 0or 1to falseor true

这种双重否定转动falseytruthy价值01falsetrue

don't believe me? go into your console and type !!0or !!1:-)

不相信我?进入您的控制台并输入!!0!!1:-)

Also, to make sure your number 1or 0are definitely coming through as a Number and not the String '1'or '0'pre-pend the value you are checking with a +e.g <input :disabled="!!+validated"/>this turns a string of a number into a Number e.g

此外,为了确保您的数字10肯定是作为数字而不是字符串'1''0'预先确定您正在检查的值,+例如,<input :disabled="!!+validated"/>这会将数字字符串转换为数字,例如

+1 = 1 +'1' = 1 Like David Morrow said above you could put your conditional logic into a method - this gives you more readablecode - just return out of the method the condition you wish to check.

+1 = 1 +'1' = 1 就像 David Morrow 上面所说的那样,您可以将条件逻辑放入一个方法中 - 这为您提供了更具可读性的代码 - 只需从方法中返回您希望检查的条件即可。

回答by Alireza

You can manipulate :disabledattribute in vue.js.

你可以:disabledvue.js 中操作属性。

It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...

它将接受一个布尔值,如果它为true,则输入被禁用,否则它将被启用...

Something like structured like below in your case for example:

例如,在您的情况下,结构类似于以下内容:

<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="validated ? false : true">

Also read this below:

另请阅读以下内容:

Conditionally Disabling Input Elements via JavaScript Expression

You can conditionally disable input elements inline with a JavaScript expression. This compact approach provides a quick way to apply simple conditional logic. For example, if you only needed to check the length of the password, you may consider doing something like this.

通过 JavaScript 表达式有条件地禁用输入元素

您可以有条件地禁用内联 JavaScript 表达式的输入元素。这种紧凑的方法提供了一种应用简单条件逻辑的快速方法。例如,如果您只需要检查密码的长度,您可以考虑做这样的事情。

<h3>Change Your Password</h3>
<div class="form-group">
  <label for="newPassword">Please choose a new password</label>
  <input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>

<div class="form-group">
  <label for="confirmPassword">Please confirm your new password</label>
  <input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>

回答by Yamen Ashraf

You may make a computed property and enable/disable any form type according to its value.

您可以创建一个计算属性并根据其值启用/禁用任何表单类型。

<template>
    <button class="btn btn-default" :disabled="clickable">Click me</button>
</template>
<script>
     export default{
          computed: {
              clickable() {
                  // if something
                  return true;
              }
          }
     }
</script>

回答by Atchutha rama reddy Karri

Try this

尝试这个

 <div id="app">
  <p>
    <label for='terms'>
      <input id='terms' type='checkbox' v-model='terms' /> Click me to enable
    </label>
  </p>
  <input :disabled='isDisabled'></input>
</div>

vue js

Vue.js

new Vue({
  el: '#app',
  data: {
    terms: false
  },
  computed: {
    isDisabled: function(){
        return !this.terms;
    }
  }
})

回答by Kobi

To toggle the input's disabledattribute was surprisingly complex. The issue for me was twofold:

切换输入的禁用属性非常复杂。我的问题是双重的:

(1)Remember: the input's "disabled" attribute is NOT a Booleanattribute.
The mere presenceof the attribute means that the input is disabled.

(1)请记住:输入的“禁用”属性不是布尔属性。
单纯的存在属性意味着输入被禁用。

However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes

然而,Vue.js 的创造者已经准备好了这个...... https://vuejs.org/v2/guide/syntax.html#Attributes

(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)

(感谢@connexo 对此...如何在 vuejs 的输入文本中添加禁用属性?

(2)In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.

(2)此外,我遇到了一个 DOM 时间重新渲染问题。当我尝试切换回来时,DOM 没有更新。

Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"

在某些情况下,“组件不会立即重新渲染。它会在下一个‘滴答’中更新。”

From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html

来自 Vue.js 文档:https://vuejs.org/v2/guide/reactivity.html

The solution was to use:

解决方案是使用:

this.$nextTick(()=>{
    this.disableInputBool = true
})

Fuller example workflow:

更完整的示例工作流程:

<div @click="allowInputOverwrite">
    <input
        type="text"
        :disabled="disableInputBool">
</div>

<button @click="disallowInputOverwrite">
    press me (do stuff in method, then disable input bool again)
</button>

<script>

export default {
  data() {
    return {
      disableInputBool: true
    }
  },
  methods: {
    allowInputOverwrite(){
      this.disableInputBool = false
    },
    disallowInputOverwrite(){
      // accomplish other stuff here.
      this.$nextTick(()=>{
        this.disableInputBool = true
      })
    }
  }

}
</script>

回答by anson

Can use this add condition.

可以使用这个添加条件。

  <el-form-item :label="Amount ($)" style="width:100%"  >
            <template slot-scope="scoped">
            <el-input-number v-model="listQuery.refAmount" :disabled="(rowData.status !== 1 ) === true" ></el-input-number>
            </template>
          </el-form-item>

回答by omarjebari

Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.

请记住,据我所知,在撰写本文时,ES6 Sets/Maps 似乎没有反应性。