uniapp 使用this指针无法修改data变量的问题

原代码:

复制代码
Sex()
            {
                console.log(this);
                uni.showActionSheet({
                    title:"选择性别",
                    itemList: ['男','女'],
                    itemColor: "#55aaff",
                    
                    success(res) {
                    
                        const n=res.tapIndex+1;
                        switch(n)
                        {
                            case 1:
                                
                                this.Sex_Text='男'
                                
                                break;
                            case 2:
                                this.Sex_Text='女'
                                break;
                        }
                        
                    }

                })
            },
复制代码

原因:在success函数中使用了箭头函数(() => {})。箭头函数不会绑定this指向,所以在箭头函数中无法访问组件实例的this。

解决办法:使用function关键字定义匿名函数来替代箭头函数。

修改后的代码:

复制代码
Sex() {
    uni.showActionSheet({
        title: "选择性别",
        itemList: ['男', '女'],
        itemColor: "#55aaff",
        success: function(res) { // 使用 function 关键字来定义函数
            const n = res.tapIndex + 1;
            switch (n) {
                case 1:
                    this.Sex_Text = '男';
                    break;
                case 2:
                    this.Sex_Text = '女';
                    break;
            }
        }.bind(this) // 使用 bind(this) 来绑定函数作用域
    })
},
复制代码

这样变量就能修改了。

posted on   Coco_一水久钟  阅读(218)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示