zoukankan      html  css  js  c++  java
  • vue2.X中使用axios

    安装axios

    命令行打开项目所在位置,执行 yarn add axios

    入口文件main.js导入

    import {
      getRequest,
      postRequest
    } from './libs/api.js'
    Vue.prototype.getRequest = getRequest
    Vue.prototype.postRequest = postRequest //注入到Vue对象

    统一封装公共请求接口(在src根目录下创建libs=》创建test.json)

    import axios from 'axios'

    //统一请求路径
    let base = 'http://localhost:8080'

    export const getRequest = (url, params) => {
      return axios({
        method: 'get',
        url: base + url,
        params: params
      })
    }

    export const postRequest = (url, params) => {
      return axios({
        method: 'post',
        url: base + url,
        data: params,
        transformRequest: [function (data) {
        let ret = ''
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret
        }],
        headers: {
          'content-Type': 'application/x-www-form-urlencoded'
        }
      })
    }

    引用请求

    export default {
      name: 'app',
      components: {
        HelloWorld
      },
      created() {
        this.getRequest('/static/test.json').then(res => {
          console.log(res.data.key)
          //赋值

        })
      }

    }

    活着Viva
  • 相关阅读:
    xml文档格式学习笔记
    Visual Studio学习记录
    Java学习笔记
    C#项目学习记录
    Linux命令行与shell脚本编程大全 学习笔记
    NodeJS (npm) 学习笔记
    Angular学习笔记
    TypeScript学习笔记
    java 项目相关 学习记录
    docker学习记录
  • 原文地址:https://www.cnblogs.com/xxySsm/p/14411264.html
Copyright © 2011-2022 走看看