uniapp踩坑记vfor循环复杂数据结构时发现点击第二个之后click事件都会报错

如题所示,循环复杂结构时,会发现点击事件会有问题。例如:

<view class="tase-content-item" v-for="(item, index) in taskItems[currentTaskIndex].data" :key="index" >
    <view @click="testClick(item)">点击1</view>
    <view @click="testClick2(item)">点击2</view>
</view>


data() {
    currentTaskIndex: 0,
    taskItems: [
        {
          id: 1,
          text: "任务大厅",
          status: "more",
          form: {
            page: 1,
            rows: 10
          },
          data: []
        },
        {
          id: 2,
          text: "我领取的",
          form: {
            page: 1,
            rows: 10
          },
          data: []
        }
      ],
}

上面,点击testClick是正常的,当点击testChild2时,发现会如下的错误

Cannot read property 'data' of undefined; [Component] Event Handler Error @ pages/task/taskList/taskList#handleEvent
TypeError: Cannot read property 'data' of undefined

一开始以为是key问题,后面排查不是。然后以为是for结构复杂,但也不是。后面发现是currentTaskIndex,切换数据问题。需要一开始默认是0,数据也渲染也出来。但在view上写taskItems[currentTaskIndex].data,可能是框架问题,不能很好处理。点击后就会报错了

解决方法,使用computed计算属性即可;

<view class="tase-content-item" v-for="(item, index) in taskLists" :key="index" >
    <view @click="testClick(item)">点击1</view>
    <view @click="testClick2(item)">点击2</view>
</view>


computed: {
    taskLists() {
      if(!this.taskItems[this.currentTaskIndex]) return
      return this.taskItems[this.currentTaskIndex].data || []
    }
  },

如果帮助到你,请收藏点赞一下吧!!!

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理