利用AXIOS请求数据,注意层级深时,匿名函数会导致this的指向改变

<script>
    window.onload = function () {
        var vm = new Vue({
            el:'.box',
            methods: {
                fnLoadData: function () {
                    // 发送请求axios完成
                    axios({
                        url:'http://t.weather.sojson.com/api/weather/city/101010100',
                        methods:'get',
                        data:{
                            dataList: []
                        }
                    })
                    .then((response) => {
                        // 因为层级比较深,匿名函数会导致this指向发生改变
                        // 这个时候使用箭头函数解决
                        alert(this);
                        this.dataList = response.data.data.forecast;
                    })
                    .catch(function () {
                        alert('网络超时, 请重新加载!')
                    });

                }
            }
        });
    }
</script>
<body>
    <div class="box">
        <button @click='fnLoadData' >请求数据</button>
    </div>
</body>
Logo

前往低代码交流专区

更多推荐