【问题标题】:How to evaluate max length of a text area using vuejs computed property?如何使用 vuejs 计算属性评估文本区域的最大长度?
【发布时间】:2021-06-21 05:38:18
【问题描述】:

我有一个文本区域,我用它来写一些东西的描述。但是,最大字符限制为 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>

【问题讨论】:

    标签: javascript vue.js computed-properties


    【解决方案1】:

    计算属性必须返回一些计算的结果。 在这里,观察者会更合适。在这种情况下,要观察的值是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: "",
              side_categories: "",
              description: "",
              commentValidationState: null
          }
        }
      },
    }
    </script>
    
    

    【讨论】:

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