axios

Posted yxqfunnysoul

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios相关的知识,希望对你有一定的参考价值。

  1. 下载: cnpm i axios
  2. main.js中的引入和使用:
import axios from ‘axios‘
Vue.prototype.$http = axios

get请求:

  <template>
  <div id="login">
    <input type="text" name="" v-model=‘user‘><br>
    <input type="text" name="" v-model=‘pass‘><br>
    <button @click=‘loginTo‘>登陆</button>
  </div>
</template>

<script>
export default {
  name: ‘login‘,
  data () {
    return {
      user:‘‘,
      pass:‘‘,
      msg: ‘Welcome to Your Vue.js App‘
    }
  },
  mounted(){
    console.log(this.$http)
  },
  methods:{
    loginTo(){
    //  alert(1);
     // console.log(this.user,this.pass)
      this.$http.get(‘http://localhost:2132/login‘,{
        params:{
          user:this.user,
          pass:this.pass
        }
      }).then((res)=>{
       // console.log(res.data)
        if(res.data.ok){
          alert(‘登陆成功‘)
        }
        else{
          alert(‘登陆失败‘)
        }
      }).catch(()=>{
        console.log(‘失败了‘)
      })
    }
  }
}
</script>

post请求:

  <template>
  <div id="login">
    <input type="text" name="" v-model=‘user‘><br>
    <input type="text" name="" v-model=‘pass‘><br>
    <button @click=‘loginTo‘>登陆</button>
  </div>
</template>

<script>
export default {
  name: ‘login‘,
  data () {
    return {
      user:‘‘,
      pass:‘‘,
      msg: ‘Welcome to Your Vue.js App‘
    }
  },
  mounted(){
    console.log(this.$http)
  },
  methods:{
    loginTo(){
    //  alert(1);
     // console.log(this.user,this.pass)
     let Parmas = new URLSearchParams();
     Parmas.append(‘user‘,this.user);
     Parmas.append(‘pass‘,this.pass);

     this.$http({
       method:‘post‘,
       url:‘http://localhost:2132/login‘,
       data:Parmas
     }).then((res)=>{
       // console.log(res.data)
        if(res.data.ok){
          alert(‘登陆成功‘)
        }
        else{
          alert(‘登陆失败‘)
        }
      }).catch(()=>{
        console.log(‘失败了‘)
      });
    }
  }
}
</script>

注意:post请求是要借助URLSearchParams对象来传输数据

以上是关于axios的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

ajax与 axios的基础讲解(附代码及接口)

项目集成element-plus和axios

回归 | js实用代码片段的封装与总结(持续更新中...)

执行带有axios的GET请求时出现401错误

前端面试题之手写promise