vue框架中使用axios,类似原生ajax调用接口

vue中:
①第一种写法
在这里插入图片描述
在这里插入图片描述

	 this.$axios.get('http://wthrcdn.etouch.cn/weather_mini', {
    
    
        params: {
    
    
          city: "北京"
        }
        })
        .then(function (response) {
    
    
        console.log(response);
        })
        .catch(function (error) {
    
    
        console.log(error);
      })

②第二种写法
在这里插入图片描述
ps:
下面这段的params那里一定要写成params,不能写成data,因为axios发送请求时,params是添加到url字符串中的用于get请求,data是添加到请求体body中的,用于post请求。

	this.$axios({
    
    
          method:'get',
          dataType:'json',
          contentType:"application/json",
          url:'http://wthrcdn.etouch.cn/weather_mini',
          params:{
    
    
            city:"北京"
          },          
      }).then((res)=>{
    
    
        console.log(res);
      })




在用axios前需配置环境

①在cmd中执行命令

npm install axios

②在package.json中就能见到这一行了
在这里插入图片描述

③在src/main.js中写下这几行
在这里插入图片描述

import axios from 'axios'

Vue.config.productionTip = false
Vue.prototype.$axios=axios
Vue.config.productionTip = false

④npm run serve就可以用axios了

猜你喜欢

转载自blog.csdn.net/weixin_44575911/article/details/111329683