VUE 中let that = this 或者 var that = this 有什么意义

在Vue开发中,由于this的动态指向特性,常常需要将this赋值给that来保持引用。例如,在事件处理函数中,this会根据调用位置改变,如在jQuery的点击事件中,this先是被点击的元素,在each循环内则变为循环中的当前元素。保存that是为了在后续操作中保持对原始对象的引用不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在vue 开发过程中我们经常会发现

 let  that = this

这样写有什么好处呢
首先要理解this,下面简述两点

1、this 永远指向一个对象
2、this 的指向取决于函数调用的位置
首先 this 指向的是一个对象,这个好理解,难就难在第二点,在JavaScript 中 一切都是对象,运行环境也是对象,this 的指向是动态的很难确定指向那个对象
举例:

$('#content').click(function(){
     //this是被点击的#content
     var that =this;
     $('.content').each(function(){
         //this是.content循环中当前的对象
         //that仍是刚才被点击我的#content
     })
 })

this指向的对象发生了变化,故需要在函数前将this指向的对象提前保存一下

代码片段:<view class="price_box_item"> <block v-for="(item,index) in priceData" :key="index" > <view class="item_con bg-image" :style="{'background-image':url(${OSSImgUrl}/images/20230403_newApp/box/offline_price_item_bg.png)}" @tap.stop="onSelectPrice(item, index)" > <view class="price_1">¥</view> <view class="price_2">{{item.price / 100}}</view> <image class="price_active" :src="${OSSImgUrl}/images/20230403_newApp/box/price_active.png" v-if="selectedPriceCode == item.priceCode" ></image> </view> </block> </view><!-- 支付组件 --> <confirm-order ref="offlinePay" :payData="payData" payType="offline" @onPay="onPay" ></confirm-order>// 支付组件 import ConfirmOrder from '@/components/confirm-order/confirm-order.vue';// 选择价位 onSelectPrice(item, index){ var that = this; uni.$u.throttle( ()=> { if(item.priceCode == this.selectedPriceCode) return this.selectedPriceCode = item.priceCode; this.payData.price = item.price / 100; console.log('this.payData.price', index) this.priceIndex = index; this.payData.name = item.price / 100 + '元双盲盒大礼包' },1000) }, 怎么通过选择不同的价位,选择对应的优惠券,优惠券在支付组件中,以下是组件中的优惠券代码片段:async mounted() { this.getAddressList(); this.getCouponList1(); }, computed:{ discountPrice(){ //优惠金额 let selectedCoupon = this.selectedCoupon; let price = this.payData.price; if(selectedCoupon.type === 1){ //折扣 return (price * ((100 - selectedCoupon.discount) / 100)).toFixed(2) }else if(selectedCoupon.type === 2){ //满减 return (selectedCoupon.subPrice / 100).toFixed(2) }else{ return 0.00 } } },
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@百思不得奇解

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值