【问题标题】:input value in vuejs using css :not[value=""]使用 css 在 vuejs 中输入值:not[value=""]
【发布时间】:2019-11-26 18:09:56
【问题描述】:

我在 VueJS 项目中使用 Bootstrap-Vue,使用类是不可能的..

我有下一个输入

<div class="input__wrapper">
   <b-form-input
     v-model="idOrNameSelected"
     class="textfield"
     :class="{'input--empty': idOrNameSelected != null}"
     @keydown.enter.native="onSubmit" />
     <label
       class="input__label">Service id or name</label>
</div>

在我的脚本部分中,我将 idOrNameSelected 定义为:

data () {
    return {
      idOrNameSelected: ''
    }
  }

在我的 scss 文件中,我有一个类似

的规则
&:focus ~ .input__label,
&:not([value=""]) ~ .input__label {
  top: 8px;
  pointer-events: none;
}

当我在输入中输入任何文本时,从来没有使用这个 css 规则,为什么?????

谢谢

【问题讨论】:

    标签: javascript css vue.js input bootstrap-vue


    【解决方案1】:

    这就是问题所在。 CSS 逻辑不了解 Vue 观察者或 v-model,因此它不会更新您的想法。退后一步,试试这个简单的例子:

    HTML

    <input class="in" type="text" value="bar" />
    <label class="lab">Test</label>
    

    CSS

    .in:not([value="foo"]) ~ .lab {
      color: crimson;
    }
    

    如您所见,标签现在是红色的。现在尝试更改value="foo",您将看到label 切换颜色。但是,您应该注意的是,它在 CSS 本身上没有任何类型的 2-way 绑定,而实际上只是在实际 DOM 中获取 当前值

    为了给你提供一个实际的解决方案,在这种情况下我会使用一个类绑定。 你可以在这里阅读它们:https://vuejs.org/v2/guide/class-and-style.html

    本质上,它允许您根据某些真实条件动态添加/删除类。而且您实际上可以在其中使用您的 v-model。

    以下是我将如何做的示例:

    <template>
      <div id="app">
        <input type="text" v-model="model">
        <label :class="{error: model === ''}">Label</label>
      </div>
    </template>
    
    <script>
    export default {
      name: "App",
      data() {
        return { model: "" };
      }
    };
    </script>
    
    <style scoped>
    .error {
      color: crimson;
    }
    </style>
    

    【讨论】:

      【解决方案2】:

      @dev-cyprium 关于 Vue 在使用 v-model 时没有将属性 value 放在输入元素上是正确的(value 实际上是元素上的 domProp)

      不过,你可以用数据属性做一个小技巧:

      <template>
        <div>
          <b-form-input id="the-input" v-model="value" :data-value="value"></b-form-input>
          <label for="the-input">Hello World</label>
        </div>
      </template>
      
      <style>
        input.form-control ~ label {
          color: red;
        }
        input.form-control[data-value=""] ~ label {
          color: blue;
        }
      </style>
      
      <script>
        export default {
          data() {
            return {
              value: ''
            }
          }
        }
      </script>
      

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 1970-01-01
        • 2011-06-10
        • 2021-02-21
        • 2021-02-20
        • 1970-01-01
        • 2020-02-18
        • 1970-01-01
        • 2018-01-02
        相关资源
        最近更新 更多