“Vue 网络应用 axios 加 vue”的版本间的差异
		
		
		
		
		
		跳到导航
		跳到搜索
		
				
		
		
	
Jihongchang(讨论 | 贡献)  | 
				Jihongchang(讨论 | 贡献)   (→完整代码示例)  | 
				||
| 第82行: | 第82行: | ||
</html>  | </html>  | ||
</syntaxhighlight>  | </syntaxhighlight>  | ||
| + | |||
| + | === 总结和注意 ===  | ||
| + | |||
| + | * <u>axios</u> 回调函数中的 <u>this</u> 已经改变,无法访问到 <u>data</u> 中的数据  | ||
| + | * 把 <u>this</u> 保存起来,回调函数中直接使用保存的 <u>this</u> 即可  | ||
| + | * 和本地应用最大的区别就是改变了 <u>数据来源</u>  | ||
2023年8月10日 (四) 01:42的最新版本
https://www.bilibili.com/video/BV12J411m7MG/?p=26
axios + vue
axios 如何结合 vue 开发网络应用
var app = new Vue({
    el:"#app",
    data:{
        joke:"搞笑的笑话"
    },
    methods:{
        getJokes:function(){
            //this.joke
            axios.get("地址").then(function(response){
               //this.joke?
            }, function(err){
            });
        }
    }
})
随机获取笑话的接口
请求地址:https://autumnfish.cn/api/joke
请求方法:get
请求参数:无
响应内容:一条随机笑话
完整代码示例
<html>
    <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>axios + vue</title>
    </head>
    <body>
        
        <div id="app">
            <input type="button" value="获取笑话" @click="getJoke">
            <p>{{ joke }}</p>
        </div>
        
        <!-- 开发环境版本,包含了有帮助的命令行警告 -->
        <script src="axios.min.js"></script>
        <script src="vue.js"></script>
        
        <script>
            /*
            接口:随机获取一条笑话
            请求地址:https://autumnfish.cn/api/joke
            请求方法:get
            请求参数:无
            响应内容:随机笑话
            */
           var app = new Vue({
            el:"#app",
            data:{
                joke:"很好笑的笑话"
            },
            methods:{
                getJoke: function(){
                    console.log(this.joke);
                    var that = this; //that 用于在 axios 的回调函数中访问 Vue 中的 data.joke
                    axios.get("https://autumnfish.cn/api/joke").then(function(response){
                        console.log(response);
                        console.log(response.data)
                        // console.log(this.joke); 不能这么用,这里的 this 不再是 Vue 里可以访问 data.joke 的 this
                        that.joke = response.data;
                    }, function(err){
                    });
                }
            }
           })
        </script>
    </body>
</html>
总结和注意
- axios 回调函数中的 this 已经改变,无法访问到 data 中的数据
 - 把 this 保存起来,回调函数中直接使用保存的 this 即可
 - 和本地应用最大的区别就是改变了 数据来源