【问题标题】:disable/enable select depending on value vuejs根据值 vuejs 禁用/启用选择
【发布时间】:2018-09-19 06:13:58
【问题描述】:

我有 2 个选择字段:

第一个字段:

ns-dropdown-item(item-id="6")    
  ns-select(:placeholder="$t('users.role')", v-model="newLeader.role",
    :options="roleOptions", @change="activeIfCoororMan")

第二个字段被禁用

ns-dropdown-item(item-id="7")    
  ns-select(:placeholder="$t('users.client')", v-model="client", 
    :options="clients", :disabled="true")

这是我的 vue 数据:

export default {
  template: template(),
  data() {
    return {
      newLeader: null,
      client: null,
      clients: [],
      errors: {},
      roleOptions: [
        {value: 'coordinator', label: this.$t('users.roleOptions.coordinator')},
        {value: 'manager', label: this.$t('users.roleOptions.manager')},
        {value: 'leader', label: this.$t('users.roleOptions.leader')},
        {value: 'leader_admin', label: this.$t('users.roleOptions.leader_admin')}
      ]
    };
  },
  methods:  {
    activeIfCoororMan() {
      if(this.newLeader.role === 'manager' || this.newLeader.role === 'coordinator') {
        console.log("remove-disabled")
      } else {
        console.log("stay-disabled")
      }
    },
  }
}

当我首先选择 coordinatorma​​nager 时,我可以在控制台中看到:remove-disable。但是,我想将 :disable 属性从第二个字段更改为 false

谢谢

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    您可以使用条件渲染:

    ns-dropdown-item(item-id="7")    
      ns-select(:placeholder="$t('users.client')", v-model="client", 
        :options="clients", 
        :disabled="newLeader.role !== 'manager' || newLeader.role !== 'coordinator'")
    

    这将仅在角色既不是经理也不是协调员时添加disabled 属性。


    但这将是一个安全问题。为什么你只是禁用它们?您根本不应该渲染元素。因此,我建议您使用v-if 语句,以便仅在条件匹配时才呈现它,否则该元素不存在于DOM中。

    ns-dropdown-item(item-id="7")    
      ns-select(:placeholder="$t('users.client')", v-model="client", 
        :options="clients", 
        v-if="newLeader.role === 'manager' || newLeader.role === 'coordinator'")
    

    【讨论】:

    • 它不起作用。错误:Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "disabled" 另外,我需要在一个函数中使用此代码来调用我的 api 服务。谢谢!
    • 从错误中,我注意到您需要将数据初始化为newLeader: {},而不是newLeader: null,
    • 谢谢,但我遇到了同样的错误。我需要模板之外的代码来调用我的 api。再次感谢你:)
    • 好像是初始化问题。尝试定义为newLeader: { role: ''}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 2011-03-11
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多