vue -- 》 axios

    xiaoxiao2022-07-06  179

    第三次课,vue 使用axios  调用后端接口 

    config-index:配置后端地址

    proxyTable: { "/v": { target: url, changeOrigin: true, pathRewrite: { "^/v": "/v" } } },

    下载依赖

    npm install --save axios

    cnpm install axios --save

    src-main : 因为vue不能直接use axios 所以  注册axios为vue的属性 $http

    import axios from 'axios' Vue.prototype.$http= axios

    页面方法调用 

    methods: { go() { this.$http({ method: "get", url: "http://127.0.0.1:8520/v/use", params: { msg: "this.msg" } }); } }

    后端数据支持

    package hc.cloud.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * Created by Administrator on 2019/5/22 0022. */ @Slf4j @RestController @RequestMapping("use") public class goIp { @GetMapping public Map<String, String> user(@RequestParam Map<String, String> map) { log.info(map.get("msg").toString()); map.put("data","Welcome to king cloud!"); return map; } }

     

     

    改良:加入接收及报错的方法

    methods: { go() { this.$http({ method: "get", url: "/v/use", params: { msg: "this.msg to you!" } }) .then(response => { this.msg = response.data.data; console.log(response); }) .catch(error => { console.log(error) }) } }

    then: 接收后端返回数据

    response.data:即后端返回数据

    response.data.data:返回数据的data属性

     

    为了提高复用性,即多个地方使用同一个接口

    api接口

    import axios from 'axios' export function send(i) { return axios({ method: "delete", url: "/v/use", params: { msg: i } }) }

    页面 

    import { send } from "../api/use.js"; go() { this.msg = "this.msg to you!"; send(this.msg) .then(response => { this.msg = response.data.data; console.log(response); }) .catch(error => { console.log(error); }); },

     

    最新回复(0)