问题描述
我有一个文本区域,我用它来写一些东西的描述。但是,最大字符限制为 5。我正在尝试使用计算属性计算我的描述的最大长度。但是,不知何故,当描述的长度超过 5 个字符的限制时,计算属性不会触发。以下是我的简单代码。
props: {
infoData: {
type: Object,default: () => {
return {
category: "",side_categories: "",description: "",commentValidationState: null
};
}
},},computed: {
descriptionValidation(){
if(this.infoData.description?.length > 5){
alert("Max length exceeded!");
}
}
}
请注意,我直接在计算属性中使用了 prop。
我的 HTML:
<b-form-group
class="col-md-12"
label="Beschreibung"
label-for="description"
invalid-Feedback="maximal 750 Zeichen"
:state="infoData.commentValidationState"
>
<b-textarea
class="form-control"
name="description"
id="description"
v-model="infoData.description"
/>
</b-form-group>
解决方法
计算属性必须返回某些计算的结果。
在这里,观察者会更合适。在这种情况下,要观察的值将是 this.infoData.description
的长度。因此,我会首先使用计算属性来获取 this.infoData.description
的长度,然后使用观察者来监视其值。
这是我的实现:
<template>
<div>
<!--- Component HTML -->
</div>
</template>
<script>
export default {
props: {
infoData: {
type: Object,default: () => {
return {
category: "",side_categories: "",description: "",commentValidationState: null
};
}
},},watch: {
descriptionLength(new_value){
if(new_value> 5){
alert("Max length exceeded!");
}
}
},computed: {
descriptionLength(){
return this.infoData.description?.length
}
}
}
</script>
这是它的父级:
<template>
<div>
<textarea v-model="infoData.description" />
<MyComponent :infoData="infoData" />
</div>
</template>
<script>
import MyComponent from '@/components/MyComponent.vue'
export default {
components: {
MyComponent,data() {
return {
infoData: {
category: "",commentValidationState: null
}
}
},}
</script>