Vue开发实例(七)Axios的安装与使用

说明:

  1. 如果只是在前端,axios常常需要结合mockjs使用,如果是前后端分离,就需要调用对应的接口,获取参数,传递参数;
  2. 由于此文章只涉及前端,所以我们需要结合mockjs使用;
  3. 由于为了方便实现效果,在这篇文章里面使用的是一级菜单,对应的代码是:【Vue开发实例(六)实现左侧菜单导航 --->>> 动态实现一级菜单】中的代码
  4. 文末附全部代码

axios和mockjs的安装与使用

一、Axios

Axios 是一个基于 promise 的 HTTP 库,类似于我们常用的 ajax。

在开发过程中,特别是前后端分离的项目,比如前端用Axios、ajax请求后端数据,后端也许当前只给了接口文档,还没有数据的返回,导致前端无法进行测试、调试,现在可以使用mock.js拦截前端ajax请求,更加方便的构造你需要的数据,大大提高前端的开发效率。

1、安装axios

vue 复制代码
npm install axios --save

在main.js全局引入axios

vue 复制代码
import axios from 'axios';
Vue.prototype.$axios =axios;

2、安装mockjs

vue 复制代码
npm install mockjs --save-dev

在src下创建文件夹mock,并创建index.js文件,输入以下测试内容:

vue 复制代码
//引入mockjs
import Mock from 'mockjs'

//使用mockjs模拟数据
Mock.mock('/test', {
  "res": 0,
  "data":
  {
    "datatime": "@datetime",//随机生成日期时间
    "weekday|1-7": 7,//随机生成1-7的数字
    "name": "@cname",//随机生成中文名字
  }
});

main.js引入此mock.js就可以进行全局拦截axios和ajax的请求了。

vue 复制代码
import './mock/index.js';

二、数据请求

1、get请求

在之前的Main1页面上编写代码

创建按钮

vue 复制代码
 <el-button @click="getTest">get数据</el-button>

创建axios请求方法

vue 复制代码
<script>
export default {
  name: "Main1",
  methods: {
    getTest() {
      this.$axios.get("/test").then((res) => {
        console.log(res.data);
      });
    },
  },
};
</script>

this.$axios.get("/test")this.$axios.get 表示使用get请求,"/test" 访问路径,刚好与之前mock.js定义的想吻合;

res 就是取得返回的数据集合,其中res.data就是我们定义好的返回数据。

浏览器中"右键-检查"或"F12"

2、post请求

添加post请求按钮

vue 复制代码
 <el-button @click="postTest">post测试1</el-button>

编写js post代码

vue 复制代码
postTest(){
   this.$axios.post("/post/test1",{id:1}).then(res=>{
        console.log(res.data)
    })
}

mock/index.js其中第2个参数指定为 post,如果我们用get请求则会提示404,只能用post

vue 复制代码
Mock.mock('/post/test1', 'post', function (param) {
  console.log('传入的参数为:', param.body)
  return {
    res: 1,
    msg: "success"
  }
});

效果展示

3、添加数据

按钮代码

vue 复制代码
<el-button @click="postAdd">add数据</el-button>

请求方法代码

vue 复制代码
postAdd(){
    this.$axios.post("/post/add",{id:1,name:'哈哈'}).then(res=>{
        console.log(res.data)
    })
}

Mockjs数据

vue 复制代码
// 定义userList数组
let userList = [];
Mock.mock('/post/add', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = true

  for (let item of userList) {
    if (item.id === id) flag = false // 判断id是否已经存在
  }

  // 如果id不存在
  if (flag) {
    userList.push(
      {
        name: body.name,
        id
      }
    )
    return {
      userList,
      res: 0,
      msg: '添加成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '添加失败'
    }
  }
});

效果展示

第一次发送请求,因为里面没有id为1的数据,所以添加成功

第二次发送请求,因为id=1的数据已经添加成功了,所以失败

重新换一个id就可以添加成功

4、修改

按钮代码

vue 复制代码
<el-button @click="postMod">mod数据</el-button>

请求代码

vue 复制代码
postMod(){
    this.$axios.post("/post/mod",{name:'哈哈',id:3}).then(res=>{
        console.log(res.data)
    })
}

mockjs数据

vue 复制代码
Mock.mock('/post/mod', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = false, index = 0;

  for (let i in userList) {
    if (userList[i].id === id) {
      flag = true // 判断id是否已经存在,存在返回true
      index = i//对应数组的下标
    }
  }
  // 如果id存在则修改
  if (flag) {
    userList[index] = body
    return {
      userList,
      res: 0,
      msg: '修改成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '修改失败'
    }
  }
});

效果展示

因为第一次修改里面没有数据,所以修改失败

先点击 添加add,再点击 修改mod

5、删除

按钮代码

vue 复制代码
<el-button @click="postDel">del数据</el-button>

请求代码

vue 复制代码
postDel() {
      this.$axios.post("/post/del", { id: 1 }).then((res) => {
        console.log(res.data);
      });
    },

mockjs数据

vue 复制代码
Mock.mock('/post/del', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = false, index = 0;

  for (let i in userList) {
    if (userList[i].id === id) {
      flag = true // 判断id是否已经存在,存在返回true
      index = i//对应数组的下标
    }
  }

  // 如果id存在则删除
  if (flag) {
    userList.splice(index, 1);
    return {
      userList,
      res: 0,
      msg: '删除成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '删除失败'
    }
  }
});

效果展示

先添加数据,再删除数据

6、查询

按钮代码

vue 复制代码
<el-button @click="postQuery">query无参数据</el-button><br /><br />
<el-button @click="postQuery2">query有参数据</el-button><br /><br />

请求代码,分别是没有参数的查询全部,有id参数的根据id来查询

(1)无参查询

postQuery(){
    this.$axios.post("/post/query",{}).then(res=>{
        console.log(res.data)
    })
}

(2)有参查询

vue 复制代码
postQuery2(){
    this.$axios.post("/post/query",{id:1}).then(res=>{
        console.log(res.data)
    })
}

mockjs数据

vue 复制代码
Mock.mock('/post/query', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)

  if (!id) {//如果id不存在,则直接返回全部
    return {
      userList,
      res: 0,
      msg: '查询成功'
    }
  }
  //id
  for (let item of userList) {
    if (item.id === id) {
      return {
        userList: [item],
        res: 0,
        msg: '查询成功'
      }
    }
  }
  // 如果id不存在则返回失败
  return {
    userList: [],
    res: 1,
    msg: '查询失败'
  }
});

效果展示

按照图示步骤执行

  1. 首先进行无参查询,查询全部,返回是空
  2. 其次是添加一条数据
  3. 接着带参查询id=1的数据

到此为止,增删改查,get、post都已测试完成,put等方法自己进行测试

附全部代码,如下:

Main1.vue

vue 复制代码
<template>
  <div>
    <span>这是Main1</span><br /><br />
    <el-button @click="getTest">get数据</el-button><br /><br />
    <el-button @click="postTest">post测试1</el-button><br /><br />
    <el-button @click="postAdd">add数据</el-button><br /><br />
    <el-button @click="postMod">mod数据</el-button><br /><br />
    <el-button @click="postDel">del数据</el-button><br /><br />
    <el-button @click="postQuery">query无参数据</el-button><br /><br />
    <el-button @click="postQuery2">query有参数据</el-button><br /><br />
  </div>
</template>

<script>
export default {
  name: "Main1",
  data() {
    return {
      userList: [{ id: 1, name: "张三" }],
    };
  },
  methods: {
    getTest() {
      this.$axios.get("/test").then((res) => {
        console.log(res.data);
      });
    },
    postTest() {
      this.$axios.post("/post/test1", { id: 1 }).then((res) => {
        console.log(res.data);
      });
    },
    postAdd() {
      this.$axios.post("/post/add", { id: 1, name: "牛牛" }).then((res) => {
        console.log(res.data);
      });
    },
    postMod() {
      this.$axios.post("/post/mod", { name: "哈哈", id: 3 }).then((res) => {
        console.log(res.data);
      });
    },
    postDel() {
      this.$axios.post("/post/del", { id: 3 }).then((res) => {
        console.log(res.data);
      });
    },
    postQuery() {
      this.$axios.post("/post/query", {}).then((res) => {
        console.log(res.data);
      });
    },
    postQuery2() {
      this.$axios.post("/post/query", { id: 1 }).then((res) => {
        console.log(res.data);
      });
    },
  },
};
</script>

<style scoped>
.el-button {
  height: auto;
}
</style>

mock/index.js

vue 复制代码
//引入mockjs
import Mock from 'mockjs'

//使用mockjs模拟数据
Mock.mock('/test', {
  "res": 0,
  "data":
  {
    "datatime": "@datetime",//随机生成日期时间
    "weekday|1-7": 7,//随机生成1-7的数字
    "name": "@cname",//随机生成中文名字
  }
});

Mock.mock('/post/test1', 'post', function (param) {
  console.log('传入的参数为:', param.body)
  return {
    res: 1,
    msg: "success"
  }
});

// 定义userList数组
let userList = [];
Mock.mock('/post/add', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = true

  for (let item of userList) {
    if (item.id === id) flag = false // 判断id是否已经存在
  }

  // 如果id不存在
  if (flag) {
    userList.push(
      {
        name: body.name,
        id
      }
    )
    return {
      userList,
      res: 0,
      msg: '添加成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '添加失败'
    }
  }
});

Mock.mock('/post/mod', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = false, index = 0;

  for (let i in userList) {
    if (userList[i].id === id) {
      flag = true // 判断id是否已经存在,存在返回true
      index = i//对应数组的下标
    }
  }
  // 如果id存在则修改
  if (flag) {
    userList[index] = body
    return {
      userList,
      res: 0,
      msg: '修改成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '修改失败'
    }
  }
});

Mock.mock('/post/del', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)
  let flag = false, index = 0;

  for (let i in userList) {
    if (userList[i].id === id) {
      flag = true // 判断id是否已经存在,存在返回true
      index = i//对应数组的下标
    }
  }

  // 如果id存在则删除
  if (flag) {
    userList.splice(index, 1);
    return {
      userList,
      res: 0,
      msg: '删除成功'
    }
  } else {
    return {
      userList,
      res: 1,
      msg: '删除失败'
    }
  }
});

Mock.mock('/post/query', 'post', function (param) {
  let body = JSON.parse(param.body) // 获取请求参数
  let id = parseInt(body.id)

  if (!id) {//如果id不存在,则直接返回全部
    return {
      userList,
      res: 0,
      msg: '查询成功'
    }
  }
  //id
  for (let item of userList) {
    if (item.id === id) {
      return {
        userList: [item],
        res: 0,
        msg: '查询成功'
      }
    }
  }
  // 如果id不存在则返回失败
  return {
    userList: [],
    res: 1,
    msg: '查询失败'
  }
});

Aside/index.vue

vue 复制代码
<template>
  <div style="height: 100%">
    <el-menu
      background-color="#545c64"
      text-color="#ffffff"
      active-text-color="#ffd04b"
      class="el-menu-vertical-demo"
      router
    >
      <el-menu-item
        :index="item.path"
        v-for="item in menu_data"
        :key="item.name"
      >
        <i :class="item.icon"></i>{{ item.name }}
      </el-menu-item>
    </el-menu>
  </div>
</template>

<script>
export default {
  name: "Aside",
  data() {
    return {
      menu_data: [
        {
          name: "一级菜单1",
          icon: "el-icon-location",
          path: "/index/menu1",
        },
        {
          name: "一级菜单2",
          icon: "el-icon-document",
          path: "/index/menu2",
        },
        {
          name: "一级菜单3",
          icon: "el-icon-setting",
          path: "/index/menu3",
        },
      ],
    };
  },
};
</script>

<style scoped>
.el-icon-location,
.el-icon-document,
.el-icon-setting {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style>
相关推荐
猿饵块27 分钟前
cmake--get_filename_component
java·前端·c++
好多吃的啊37 分钟前
背景图鼠标放上去切换图片过渡效果
开发语言·javascript·ecmascript
大表哥638 分钟前
在react中 使用redux
前端·react.js·前端框架
Passion不晚40 分钟前
打造民国风格炫酷个人网页:用HTML和CSS3传递民国风韵
javascript·html·css3
十月ooOO43 分钟前
【解决】chrome 谷歌浏览器,鼠标点击任何区域都是 Input 输入框的状态,能看到输入的光标
前端·chrome·计算机外设
qq_3391911443 分钟前
spring boot admin集成,springboot2.x集成监控
java·前端·spring boot
pan_junbiao1 小时前
Vue使用代理方式解决跨域问题
前端·javascript·vue.js
明天…ling1 小时前
Web前端开发
前端·css·网络·前端框架·html·web
子非鱼9211 小时前
【JavaScript】LeetCode:41-45
开发语言·javascript·leetcode·链表·二叉树
ROCKY_8171 小时前
web前端-HTML常用标签-综合案例
前端·html