axios 官网:axios中文网

方式一:将 axios 绑定到 vue 原型上

安装:

npm install axios

main.js中导入并绑定

import Vue from 'vue'
import App from './App'
import axios from 'axios'

Vue.prototype.$axios = axios

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

使用:

<template>
  <div id="app">
    <button @click="handleClick">点击</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    handleClick() {
    //   this.$axios({
    //     method: "get",
    //     url: "http://localhost:8081/hello"
    //   }).then(res => {
    //     console.log(res.data);
    //   });

      this.$axios.get("http://localhost:8081/hello").then(response => {
        console.log(response.data);
      });
    }
  }
};
</script>

<style></style>

方式二:使用 vue-axios

安装:

npm install --save axios vue-axios

main.js 中安装

import Vue from 'vue'
import App from './App'

import axios from 'axios'
import VueAxios from 'vue-axios'
// VueAxios 与 axios 的位置不能交换,否则出现 TypeError: Cannot read property 'protocol' of undefined
Vue.use( VueAxios , axios)

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

使用:

<template>
  <div id="app">
    <button @click="handleClick">点击</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    handleClick() {
    //   this.axios({
    //     method: "get",
    //     url: "http://localhost:8081/hello"
    //   }).then(res => {
    //     console.log(res.data);
    //   });

      this.axios.get("http://localhost:8081/hello").then(response => {
        console.log(response.data);
      });
    }
  }
};
</script>

<style></style>

补充:发送 post 请求

this.axios({
    method: "post",
    url: "http://localhost:8081/hello",
    data: {
        username: "admin",
        password: "123"
    }
}).then((res)=>{
    console.log(res.data);
})

后端 springboot 代码

@RestController
@CrossOrigin
public class HelloController {
    @RequestMapping("hello")
    public String hello(@RequestBody Map<String, String> username) {
        System.out.println(username);
        return "Hello world!";
    }
}

结果:


在这里插入图片描述


在这里插入图片描述


Logo

前往低代码交流专区

更多推荐