问题
I have Vue app and I would like to add Facebook inspired buttons inlined in a comment form. I had plain JS prototype that was working. But I cannot make it work inside Vue component. I have implemented two variants, both are called but the style is not changed in either.
- callback listening to the input event
- condition in the class attribute
The sandbox is there: https://codesandbox.io/s/black-mountain-tryro
Callback variant:
<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";
}
},
This one fails that Vue component has no syle property: textComment.style.padding
CSS variant:
<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;
}
This one does not modify the style regardless of wrapText computed property value.
How to make it work? Which approach is better?
回答1:
Your class syntax is wrong. :class
expects an object with the class name as key and true
or false
as values. Try it like this:
:class="{icons_long: !wrapIcons}"
In my opinion, i would go with the CSS approach
回答2:
Another and valid syntax is keeping your own and adding back tick ` and string interpolation :
:class="`${wrapIcons ? 'textarea_short' : 'textarea_long'}`"
来源:https://stackoverflow.com/questions/63166772/vue-js-apply-css-style-for-textarea-based-on-text-length