vue 组件开发 ---- click事件 和 v-model 的数据更新时间差解决方法

需求描述

  1. 使用 vue 的 vant 框架的 van-checkbox 组件实现列表的选择;
  2. 选择完成请求对应的数据后返回上一页面!

页面效果和代码

  1. 页面效果
    在这里插入图片描述

  2. 页面HTML

<div class="rui-from-li rui-flex-ac" v-for="item,index in userInfo.shops">
      <div class="rui-fg">
        <div class="rui-flex-ac">
          <img :src="icon.changeShopIcon" class="rui-change-icon" alt="">
          <div class="rui-fs30 rui-ml25 rui-line1 rui-fg">{
   
   {item.hallname}}</div>
        </div>
        <div class="rui-flex-ac rui-mt20">
          <img :src="icon.changeAddressIcon" class="rui-change-icon" alt="">
          <div class="rui-fs30 rui-ml25 rui-line1 rui-fg">{
   
   {item.halladdress}}</div>
        </div>
      </div>
      <van-checkbox v-model="item.checked" @click="getCurrentShop(index, item)" checked-color="#e24c4e"></van-checkbox>
    </div>

click 事件和 v-model 数据双向绑定的处理

getCurrentShop(index, shop){
          console.log(shop)
          console.log(JSON.stringify(shop))
          if(!shop.checked){
            console.log('取消选中,不执行切换操作!')
            return false;
          }
          this.qywap.getShopIdBySharInfo({shareId: shop.shareId}).then(res => {
            localStorage.setItem('skid', res.skid)
            localStorage.setItem('shopId', res.tyfoShopid)
            localStorage.setItem('scene',shop.shareId)
            history.back()
          })
        }
      }

点击 getCurrentShop 函数输出结果

在这里插入图片描述

click 事件的执行在 v-model 的修改之前,导致的结果是取消操作,不执行打断失效!

解决办法

  1. 由于 v-model 数据是双向的,所以我认为可以自己直接再事件中先改变!
getCurrentShop(index, shop){
		  this.userInfo.shops[index].checked = !this.userInfo.shops[index].checked;
          console.log(shop)
          console.log(JSON.stringify(shop))
          if(!shop.checked){
            console.log('取消选中,不执行切换操作!')
            return false;
          }
          this.qywap.getShopIdBySharInfo({shareId: shop.shareId}).then(res => {
            localStorage.setItem('skid', res.skid)
            localStorage.setItem('shopId', res.tyfoShopid)
            localStorage.setItem('scene',shop.shareId)
            history.back()
          })
        }
      }

解决后输出

在这里插入图片描述

由于没有百度到类似的问题,所以可能是用的方法错误,如有知道正确方法的,请告知!此篇博客只作为开发过程遇到问题的记录!

猜你喜欢

转载自blog.csdn.net/m0_38082783/article/details/115704499