Axios中this无法访问

132 阅读1分钟

关于axios中this无法访问的问题

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <table>
            <tr v-for="user in userList">
                <td>{{user.name}}</td>
                <td>{{user.age}}</td>
            </tr>
        </table>
    </div>
    <script src="vue.min.js"></script>
    <script src="axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                userList: []
            },
            created() {
                this.getUserList()
            },
            methods: {
                getUserList() {
                    // axios里面的函数导致了this的实例不对了, 
                    // 里面要用this修改对象的值会出错,需要单独定义个变量代替this的vue实例,
                    // 然后用那个变量替代vue的实例来修改值 
                    let that = this
                    axios.get("user.json")
                        //   成功
                        .then(function (response) {
                            console.log(response);
                            // 注意 直接用 this,这个是window对象,不能直接改变vue对象的值
                            // 提前声明this对象
                            that.userList = response.data.data
                        })
                        // 失败
                        .catch(error => {
                            console.log("error", error);
                        })
                }
            }
        })
    </script>
</body>

</html>

user.json

    "code":200,
    "message":"成功访问user.json",
    "data":[
        {"name":"lucy","age":18},
        {"name":"mary","age":19},
        {"name":"nick","age":20}
    ]
}