vue里面的axios封装 外加增删改查

一般来说我们都是直接写axios的请求,每个请求都要写,到时候的维护不方便,不如封装好,这样改动的话不至于一发动全身

我写了个两个js文件一个是http.js 一个是 api.js  

http.js里面主要写了请求方法  api.js 里面主要是写的 请求的路由及方法

我写了一个增删改查的demo

看代码 http.js 文件里的

import axios from ‘axios‘;
axios.defaults.baseURL="http://127.0.0.1:8000/";
axios.defaults.timeout=10000;
axios.defaults.headers.post[‘Content-Type‘] = ‘application/json‘;
axios.defaults.headers.put[‘Content-Type‘] = ‘application/json‘;

// export function get_axios(url,params){
//   axios.get(url,{params:params})
// }

// GET
export function axios_get(url,params){
    return new Promise(
        (resolve,reject)=>{
            axios.get(url,{params:params})
            .then(res=>{
                console.log("封装信息的的res",res)
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}
// POST
export function axios_post(url,data){
    return new Promise(
        (resolve,reject)=>{
            console.log(data)
            axios.post(url,data)
            .then(res=>{
                console.log("封装信息的的res",res)
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}
// PUT
export function axios_put(url,data){
    return new Promise(
        (resolve,reject)=>{
            console.log(data)
            axios.put(url,data)
            .then(res=>{
                console.log("封装信息的的res",res)
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}

// DELETE
export function axios_delete(url,params){
    return new Promise(
        (resolve,reject)=>{
            axios.delete(url,{params:params})
            .then(res=>{
                console.log("封装信息的的res",res)
                resolve(res.data)
            }).catch(err=>{
                reject(err.data)
            })
        }
    )
}

接下来是 api.js 的代码

import {axios_get,axios_post,axios_put,axios_delete} from ‘./http.js‘

export const send_get = p  => axios_get("app02/books/",p)    //增
export const send_post = p  => axios_post("app02/books/",p)   //删
export const send_put = p  => axios_put("app02/books/",p)    //改
export const send_delete = p  => axios_delete("app02/books/",p)  //查

放入写的前端页面吧虽然很难看,但是逻辑还算是清晰

XXX.vue

vue里面的axios封装 外加增删改查
  1 <template>
  2   <div>
  3     <h1>{{message}}</h1>
  4     <h2>展示</h2>
  5       <table>
  6         <tr v-for="k in books_list">
  7           <td>{{k.name}}</td>
  8           <td>{{k.price}}</td>
  9           <td>{{k.num}}</td>
 10         </tr>
 11       </table>
 12       <h2>添加</h2>
 13       数据名称<input type="text" v-model="books.name"><br>
 14       价格<input type="text" v-model="books.price"><br>
 15       数量<input type="text" v-model="books.num"><br>
 16       <button @click="AddBook()">添加</button>
 17       <br>
 18       <br>
 19       <br>
 20       <br>
 21       <h2>修改</h2>
 22       选择要修改的
 23       <select  v-model="outname"  >
 24           <option value="" id="0" style="display: none;" disabled selected>请选择</option>
 25           <option v-for="k in books_list" :id="k.id" v-text="k.name"></option>
 26       </select><br>
 27       数据名称<input type="text" v-model="books.name"><br>
 28       价格<input type="text" v-model="books.price"><br>
 29       数量<input type="text" v-model="books.num"><br>
 30       <button @click="PutBook()">修改</button>
 31       <h2>删除</h2>
 32       <select  v-model="name"  >
 33           <option value="" id="0" style="display: none;" disabled selected>请选择</option>
 34           <option v-for="k in books_list" :id="k.id" v-text="k.name"></option>
 35       </select><button @click="DelBook()">删除</button><br>
 36 
 37   </div>
 38 </template>
 39 
 40 
 41 <script>
 42   import {send_get,send_post,send_put,send_delete} from ‘../api/api.js‘
 43   export default {
 44     data(){
 45       return{
 46         outname:‘‘,
 47         books_list:[],
 48         name:‘‘,
 49         // price:0,
 50         // num:0,
 51         books:{‘name‘:‘‘,‘num‘:0,‘price‘:0},
 52         message:‘‘
 53       }
 54     },
 55     mounted() {
 56       this.getbook()
 57     },
 58     methods:{
 59       getbook(){
 60         var _this = this;
 61         send_get({}).then(res =>{
 62           console.log(res)
 63           _this.books_list = res.data
 64           console.log(_this.books_list)
 65         })
 66       },
 67       AddBook(){
 68         console.log(this.books)
 69         var _this = this;
 70         send_post(_this.books).then(res=>{
 71           console.log(‘添加‘,res)
 72           if(res.code==200){
 73             _this.message = ‘添加成功‘
 74           }else{
 75              _this.message = ‘添加失败‘
 76           }
 77 
 78         })
 79       },
 80       PutBook(){
 81         console.log(this.outname)
 82         var _this = this;
 83         _this.books[‘outname‘] = _this.outname
 84         send_put(_this.books).then(res=>{
 85           console.log(‘修改‘,res)
 86           if(res.code==200){
 87             _this.message = ‘修改成功‘
 88           }else{
 89              _this.message = ‘修改失败‘
 90           }
 91 
 92         })
 93       },
 94       DelBook(){
 95         var _this = this;
 96         console.log(_this.name)
 97         var books = {‘name‘:_this.name}
 98         send_delete(books).then(res=>{
 99           if(res.code==200){
100             _this.message = ‘删除成功‘
101           }else{
102              _this.message = ‘删除失败‘
103           }
104         })
105       }
106     },
107 
108   }
109 </script>
110 
111 <style scoped>
112 
113 </style>
Vue

后台我用的是python中的Django框架

这是我的model.py

vue里面的axios封装 外加增删改查
class Books(models.Model):
    name = models.CharField(max_length=32,null=True)
    price = models.IntegerField(null=True)
    num = models.IntegerField(null=True)

    class Meta:
        db_table = books
model.py

接下来是序列化

vue里面的axios封装 外加增删改查
class BookSer(serializers.ModelSerializer):
    name = serializers.CharField(max_length=32)
    price = serializers.IntegerField(allow_null=True)
    num = serializers.IntegerField(allow_null=True)

    class Meta:
        model = Books
        fields = __all__
serializer.py

路由就不写了,太简单了直接吧views里面的代码放过来吧

vue里面的axios封装 外加增删改查
class BookAPIView(APIView):
    def get(self,request):
        book = Books.objects.all()
        books = BookSer(instance=book,many=True).data
        data = {
            code:200,
            data:books
        }
        return Response(data)


    def post(self,request):
        print(request.data)
        book = request.data.copy()
        book_is = BookSer(data=book)
        try:
            book_is.is_valid()
            book_is.save()
        except Exception as e:
            print(e)

        data = {
            code:200,

        }
        return Response(data)

    def put(self,request):
        print(request.data)

        book = request.data.copy()
        book_ = Books.objects.filter(name=book.get(outname)).first()

        book_is = BookSer(book_,data=book)
        try:
            book_is.is_valid()
            book_is.save()
        except Exception as e:
            print(e)

        data = {
            code:200,

        }
        return Response(data)

    def delete(self,request):
        name = request.query_params.get(name)
        Books.objects.filter(name=name).delete()
        data = {
            code:200
        }
        return Response(data)
Views.py

 

vue里面的axios封装 外加增删改查

上一篇:微软开源分布式高性能GB框架LightGBM Ubuntu、CentOS下编译安装过程


下一篇:开源Puppet 4:提供更高能力和可靠性