【问题标题】:VUE: Uncaught TypeError: Cannot read property 'length' of undefinedVUE:未捕获的类型错误:无法读取未定义的属性“长度”
【发布时间】:2021-05-03 11:19:53
【问题描述】:

我正在关注一个 vue 教程。下面是实现文本区域字符限制的函数,

<form action="" class="create-twoot" @submit.prevent="createnewTwoot">
   <label for="new-twoot">New Twoot</label>
   <p>{{char_limit}}/180</p>
   <textarea name="" id="new-twoot" cols="30" rows="4" v-model="newTwootcontent"></textarea>
   <br/>
   <label for="newTwootType">Twoot Type</label>
   <select name="TwootType" id="newTwootType" v-model="twootType">
      <option :value="option.name" v-for="(option,index)  in twootTypes" :key="index">
         {{option.value}}
      </option>
   </select>
   <br/>
   <button>Tweet</button>
</form>

JS 代码

export default {
  name: 'Userprofile',
  newTwootcontent: '',
  twootType: 'instant',
  
    computed:{
    char_limit(){
      return this.newTwootcontent.length;
    },
    fullname(){
      return `${this.users.fname} ${this.users.lname}`;
    }
  },
}

其他一切正常,但 char_limit 给出以下错误

(我没有发布数据、方法等,因为它们工作正常)

Cannot read property 'length' of undefined
    at Proxy.char_limit (Userprofile.vue?5045:102)

谁能告诉我代码有什么问题

【问题讨论】:

  • 首先查看基础知识、数据和方法:vuejs.org/v2/guide/instance.html#Data-and-Methods
  • @LawrenceCherone 我已经添加了方法和数据并且它正在工作 find ,请让我知道我是否也应该发布该代码
  • 按原样发布代码,否则按原样定义 vue 实例上的数据中应该包含的内容是错误的,因此会出现错误
  • @LawrenceCherone 根据 Amaarrockz 的回答,我在数据中定义了 newTwootcontent,它解决了这个问题,谢谢

标签: javascript vue.js


【解决方案1】:

在数据部分中定义变量,如

export default {
  name: 'Userprofile',
  data() {
    return {
      newTwootcontent: '',
      twootType: 'instant',
    };
  }
    computed:{
    char_limit(){
      return this.newTwootcontent.length;
    },
    fullname(){
      return `${this.users.fname} ${this.users.lname}`;
    }
  },
}

【讨论】:

  • 确定几分钟后就可以接受,只需澄清一下所有属性都需要在数据中定义吗?请确认
  • 是的,所有变量都应该在数据中定义
  • 只有这样才能使用'this'操作符访问它们。也不要将计算和方法与数据变量混淆,因为它们也可以使用“this”操作符访问
猜你喜欢
  • 2013-11-24
  • 2019-11-22
  • 2020-07-19
  • 2020-04-19
相关资源
最近更新 更多