vue 内部使用axios需注意this的使用

三种写法

以下有三种写法,注意 第一种 的坑!!!其余两种任意采用一种皆可。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Pay attention to this when using Axios in Vue.</title>
</head>
<body>
<div id="app">
    <input type="button" value="this get请求" @click="thisGet">
    <input type="button" value="self get请求" @click="selfGet">
    <input type="button" value="other get请求" @click="otherGet">
    <input type="text" v-model="text">
</div>
<!-- development version, includes helpful console warnings -->
<!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            text: 'test',
            url: 'http://localhost/api/test',
        },
        methods: {
            // fail
            thisGet(){
                console.log('thisGet-start');
                console.log('origin:'+this.text);
                axios.get(this.url).then(
                    function(res){
                        console.log(res.status);
                        this.text = 'thisGet:'+res.status;
                        console.log('thisGet-end:'+this.text);
                    }
                );
            },
            // success
            selfGet(){
                console.log('selfGet-start');
                console.log('origin:'+this.text);
                let self = this;
                axios.get(self.url).then(
                    function(res){
                        console.log(res.status);
                        self.text = 'selfGet:'+res.status;
                        console.log('selfGet-end:'+self.text);
                    }
                );
            },
            // success
            otherGet(){
                console.log('otherGet-start');
                console.log('origin:'+this.text);
                axios.get(this.url).then((res) => {
                        console.log(res.status);
                        this.text = 'otherGet:'+res.status;
                        console.log('otherGet-end:'+this.text);
                    },function(error) {
                        console.log(error);
                    }
                );
            },
        },
    });
</script>
</body>
</html>

测试结果

在这里插入图片描述

箭头函数与 关键词function的区别

参考:https://blog.csdn.net/github_38851471/article/details/79446722

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值