succcess回调中调用同一个methods内的其它函数

uni.showModal({
		title: '提示',
		content: '删除后不可恢复!',
		success: function (res) {
			if (res.confirm) {
				console.log('用户点击确认');
				this.deleteShare(id);
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});

场景:
现在有一个删除提示框,
用户点击确认后调用methods中的deleteShare方法
在这里插入图片描述

但是却会报错:deleteShare方法未定义在这里插入图片描述
解决方法:
第一步:定义全局变量that

<script>
	import store from '@/store'
	import {getShareDetail,deleteShareDetail} from '@/api/Share/index.js'
	var that //定义变量that

	export default {}
		//...此处省略多余代码
</script>

第二步:在生命周期created中使that = this

<script>
	import store from '@/store'
	import {getShareDetail,deleteShareDetail} from '@/api/Share/index.js'
	var that

	export default {
		created(){
			that = this
		},
		.......

第三步:在success回调方法中使用that指向需要调用的方法(deleteShareDetail)

<script>
	import store from '@/store'
	import {getShareDetail,deleteShareDetail} from '@/api/Share/index.js'
	var that

	export default {
		created(){
			that = this
		},

		data() {
			return {
				ShareDetailPicture:[],
			}
		},
		methods: {
			deleteShare(id) {
				deleteShareDetail(id).then((res)=>{
				uni.showToast({
					title:"删除成功"
					})
				}).catch((err)=>{
					console.log("网络异常")
				})
			},
			

			deleteConfrim(id,form){
				uni.showModal({
				title: '提示',
				content: '删除后不可恢复!',
				success: function (res) {
					if (res.confirm) {
						that.deleteShare(id); //这里使用that
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
				});
			},
		},

		onLoad(option){
			this.role = store.getters.roles
			this.form.sessionId = option.Id
		},

		onShow(){
			this.getShare();
		}
	}
</script>

完成以上步骤就可以正常调用了。

方法2:利用箭头函数this为静态的特性。
箭头函数向外层作用域中一层层查找this,直到有this的定义
详见:Vue学习之箭头函数的使用和this指向

步骤:

uni.showModal({
		title: '提示',
		content: '删除后不可恢复!',
		success: res => {  //这里改写成箭头函数就可以了
			if (res.confirm) {
				console.log('用户点击确认');
				this.deleteShare(id);  
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值