【问题标题】:Vue.js - Apply CSS style for textarea based on text lengthVue.js - 根据文本长度为 textarea 应用 CSS 样式
【发布时间】:2020-11-19 19:42:25
【问题描述】:

我有 Vue 应用程序,我想在评论表单中添加受 Facebook 启发的按钮。我有一个可以工作的普通 JS 原型。但是我不能让它在 Vue 组件中工作。我已经实现了两个变体,都被调用了,但是样式都没有改变。

  1. 回调监听输入事件
  2. 类属性中的条件

沙盒在那里:https://codesandbox.io/s/black-mountain-tryro

回调变体:

<b-form-textarea
  class="textarea"
  ref="textareaRef"
  rows="1"
  max-rows="8"
  @input="adjustIconsInTextarea"
  placeholder="Type something"
  v-model="text"
></b-form-textarea>

adjustIconsInTextarea() {
  const textComment = this.$refs.textareaRef;
  const icons = this.$refs.iconsRef;
  if (textComment.value.length > 140) {
    textComment.style.padding = "13px 50px 34px 32px";
    icons.style.top = "-36px";
    icons.style.right = "72px";
  } else {
    textComment.style.padding = "10px 174px 5px 28px";
    icons.style.top = "-45px";
    icons.style.right = "68px";
  }
},

这个失败是因为Vue组件没有syle属性:textComment.style.padding

CSS 变体:

<b-form-textarea
  class="textarea"
  :class="wrapIcons ? 'textarea_short' : 'textarea_long'"
  rows="1"
  max-rows="8"
  placeholder="Type text"
  v-model="text"
></b-form-textarea>

computed: {
  wrapIcons() {
    return this.text.length > 140;
  }

.textarea {
  height: 40px;
  overflow-y: hidden;
}

.textarea_short {
  padding: 10px 174px 5px 28px;
}

.textarea_long {
  padding: 13px 50px 34px 32px;
}

无论 wrapText 计算的属性值如何,这个都不会修改样式。

如何让它发挥作用?哪种方法更好?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component bootstrap-vue


    【解决方案1】:

    您的类语法错误。 :class 需要一个对象,其类名作为键,truefalse 作为值。试试这样:

    :class="{icons_long: !wrapIcons}"
    

    在我看来,我会选择 CSS 方法

    【讨论】:

      【解决方案2】:

      另一种有效的语法是保留您自己的并添加反引号 ` 和字符串插值:

      :class="`${wrapIcons ? 'textarea_short' : 'textarea_long'}`" 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-17
        • 1970-01-01
        • 1970-01-01
        • 2012-02-29
        相关资源
        最近更新 更多