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

17次阅读

共计 1032 个字符,预计需要花费 3 分钟才能阅读完成。

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

<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 || []}
  },

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

正文完
 0