如何使用axios进行Vue和后端的数据交互?

axios的简单使用

Axios是一个开源的可以用在浏览器端和NodeJS的异步通信框架,它的主要作用就是实现Ajax异步通信。
1.安装axios

npm install axios vue-axios --save

2.在main.js中引入axios

import axios from 'axios'

Vue.config.productionTip = false;
//设置默认请求的路径(http://localhost:8088为请求后端的路径)
axios.defaults.baseURL = "http://localhost:8088"
Vue.prototype.$axios = axios;

3.使用axios请求后端数据

<script>
  export default {
    name: "UserManager",
    data(){
      return{
      //声明student数组
        student:[]
      }
    },
    //vue生命周期钩子函数,用来初始数据
    mounted(){
    //初始化student
      this.getStudent();

    },
    methods : {
    //通过调用后端接口得到student集合
      getStudent(){
      //get为请求方式,请求路径为baseURL+''即http://localhost:8088/student/index
      //then回调函数,res为请求返回的结果
        this.$axios.get('/student/index').then(res =>{
          console.log(res);
          //将res.data里面的数据赋值给student数组
          this.student = res.data;
        })

      },
      del(id){
        if (confirm("您确定要删除吗?")) {
        //带参用+号连接即可
          this.$axios.get('/student/delete/'+id).then(res =>{
            if(res){
              for (var i = 0; i <this.student.length ; i++) {
                if(id==this.student[i].id){
                  this.removeTodo(i)
                }
              }
            }
          })
        } else {
          return false;
        }

      },

    removeTodo (index){
      this.student.splice(index, 1);
    }
    }
  }
</script>

4.vue绑定数据

<template>
  <div>
    用户首页
    <table border="1px">
      <thead>
      <tr>
        <th>
          <div><input type="checkbox"></div>
        </th>
        <th>id</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>班级</th>
        <th>性别</th>
        <th>操作</th>

      </tr>
      </thead>
      <tbody>
      //使用v-for循环遍历
      <tr v-for = "stu in student" :key="stu.id">
        <td>
          <div><input type="checkbox"/></div>
        </td>
        //mustache语法{{}}获取对象属性数据
        <td>{{stu.id}}</td>
        <td>{{stu.name}}</td>
        <td>{{stu.age}}</td>
        <td>{{stu.classroom}}</td>
        <td>{{stu.sex}}</td>

        <td>
          <a title="编辑"  onclick="" href="javascript:;">编辑</a>
          <a title="删除"  href="#" @click="del(stu.id)">删除</a>
        </td>
      </tr>
      </tbody>
    </table>

  </div>
</template>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值