Vue.js - 根据文本长度为文本区域应用 CSS 样式
Vue.js - Apply CSS style for textarea based on text length
我有 Vue 应用程序,我想在评论表单中添加内联的受 Facebook 启发的按钮。我有可以正常工作的普通 JS 原型。但是我不能让它在 Vue 组件中工作。我已经实现了两个变体,都被调用了,但风格都没有改变。
- 监听输入事件的回调
- class 属性中的条件
沙箱在那里: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 计算的 属性 值如何,这个都不会修改样式。
如何让它发挥作用?哪种方法更好?
您的 class 语法错误。 :class
需要一个以 class 名称作为键并以 true
或 false
作为值的对象。像这样尝试:
:class="{icons_long: !wrapIcons}"
在我看来,我会采用 CSS 方法
另一种有效的语法是保留您自己的并添加回勾 ` 和字符串插值:
:class="`${wrapIcons ? 'textarea_short' : 'textarea_long'}`"
我有 Vue 应用程序,我想在评论表单中添加内联的受 Facebook 启发的按钮。我有可以正常工作的普通 JS 原型。但是我不能让它在 Vue 组件中工作。我已经实现了两个变体,都被调用了,但风格都没有改变。
- 监听输入事件的回调
- class 属性中的条件
沙箱在那里: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 计算的 属性 值如何,这个都不会修改样式。
如何让它发挥作用?哪种方法更好?
您的 class 语法错误。 :class
需要一个以 class 名称作为键并以 true
或 false
作为值的对象。像这样尝试:
:class="{icons_long: !wrapIcons}"
在我看来,我会采用 CSS 方法
另一种有效的语法是保留您自己的并添加回勾 ` 和字符串插值:
:class="`${wrapIcons ? 'textarea_short' : 'textarea_long'}`"