Vue-resource Crud Example

Source: Internet
Author: User
Get Request

var demo = new Vue ({
    el: ' #app ',
    data: {
        gridcolumns: [' customerId ', ' companyName ', ' ContactName ', ' phone '],
        griddata: [],
        apiurl: ' Http://211.149.193.19:8080/api/customers '
    },
    ready:function () {
        This.getcustomers ()
    },
    methods: {
        getcustomers:function () {this
            . $http. Get (This.apiurl)
                . Then (response) => {this
                    . $set (' Griddata ', Response.data)
                })
                . catch (function (response) {
                    Console.log (Response)}}}
)
The then method of this program only provides the Successcallback, and omits the Errorcallback.
The Catch method is used to catch the exception of the program, the Catch method and the Errorcallback are different, the errorcallback is invoked only when the response fails, and the catch is invoked as long as the program goes wrong when the entire request is in response.
Within the callback function of the then method, you can also use the this,this directly to point to the Vue instance:
Getcustomers:function () {this
    . $http. Get (This.apiurl)
        . Then (response) => {this
            . $set (' Griddata ', response.data)
        })
        . catch (function (response) {
            Console.log (response)
        })
}
To reduce the scope chain search, it is recommended to use a local variable to receive this.

Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/http-get.html JSONP Request

Getcustomers:function () {this
    . $http. Jsonp (This.apiurl). Then (function (response) {This
        . $set (' Griddata ', Response.data)}
    )
}
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/http-jsonp.html

POST Request

var demo = new Vue ({el: ' #app ', data: {show:false, gridcolumns: [{name: ' Customeri
        d ', iskey:true}, {name: ' CompanyName '}, {name: ' ContactName ' }, {name: ' phone '}], Griddata: [], Apiurl: ' Http://211.149.193.19:8080/api/custo Mers ', item: {}}, Ready:function () {this.getcustomers ()}, methods: {closedial
            Og:function () {this.show = false}, Getcustomers:function () {var VM = this VM. $http. Get (Vm.apiurl). Then (response) => {vm. $set (' Griddata ', response . Data)}}, Createcustomer:function () {var VM = this VM. $http. P
                    OST (Vm.apiurl, Vm.item). Then ((response) => {vm. $set (' item ', {})
   Vm.getcustomers ()             }) This.show = False}}) 

Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/http-post.html

Put request

Updatecustomer:function () {
    var vm = This
    vm. $http. Put (This.apiurl + '/' + vm.item.customerId, Vm.item)
        . Then ((response) => {
            vm.getcustomers ()
        })
}

Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/http-put.html

Delete Request

Deletecustomer:function (Customer) {
    var vm = This
    vm. $http. Delete (This.apiurl + '/' + Customer.customerid)
        . Then ((response) => {
            vm.getcustomers ()
        })
}


Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/http-delete.html use resource service

Vue-resource provides an alternative way to access the Http--resource service, which includes the following default action, resource service:

Get: {method: ' Get '},
Save: {method: ' POST '},
query: {method: ' Get '},
Update: {method: ' Put '},
remove: {method: ' delete '},
Delete: {method: ' delete '}
The resource object also has two ways of accessing it:
Global access: vue.resource instance access: this. $resource resource can be used in conjunction with URI template, the apiurl of the following example is set to {/ID}:
Apiurl: ' Http://211.149.193.19:8080/api/customers{/id} '
Get RequestThe GET request is sent using the Get method, and the following request does not specify {/ID}.

Getcustomers:function () {

    var resource = this. $resource (this.apiurl)
        vm = this

    resource.get ()
        . Then ( (response) => {
            vm. $set (' Griddata ', Response.data)
        }
        . catch (function (response) {
            Console.log ( Response)}
        )
}
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/resource-get.html POST RequestThe POST request is sent using the Save method, and the following request does not specify {/ID}.
Createcustomer:function () {
    var resource = this. $resource (this.apiurl)
        vm = This
        
    resource.save ( Vm.apiurl, Vm.item)
        . Then ((response) => {
            vm. $set (' item ', {})
            vm.getcustomers ()
        })
    This.show = False
}
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/resource-post.html Put requestUsing the Update method to send the put request, the following request specifies {/ID}.
Updatecustomer:function () {
    var resource = this. $resource (this.apiurl)
        vm = This
        
    resource.update ({ID: Vm.item.customerId}, Vm.item)
        . Then ((response) => {
            vm.getcustomers ()
        })
}
{/ID} is equivalent to a placeholder that is replaced when the actual argument is passed in.
For example, the vm.item.customerId in {id:vm.item.customerId} is 12, and the request URL sent is:
Http://211.149.193.19:8080/api/customers/12
Demo Address: Http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/resource-post.put Delete RequestThe delete request is sent using the Remove or Delete method, and the following request specifies {/ID}.
Deletecustomer:function (Customer) {
    var resource = this. $resource (this.apiurl)
        vm = This
        
    resource.remove ({id:customer.customerId})
        . Then ((response) => {
            vm.getcustomers ()
        })
}
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/resource-delete.html using InteceptorInterceptors can do some processing before the request is sent and after the request is sent.


Basic Usage
Vue.http.interceptors.push (Request, Next) => {
        //...
        Processing logic before the request is sent
        //...
    Next ((response) => {
        //...
        Processing logic after the request is sent
        //...
        Depending on the state of the request, the response parameter is returned to Successcallback or Errorcallback return
        response
    })
})
Before response returns to Successcallback or Errorcallback, you can modify the contents of the response or do some processing.
For example, if the status code of the response is 404, you can display a friendly 404 interface.
If you don't want to use a lambda function, you can use it as a civilian:
Vue.http.interceptors.push (function (request, next) {
    //...
    Processing logic before the request is sent
    //...
    Next (function (response) {
        //...
        Processing logic after the request is sent
        //...
        Depending on the state of the request, the response parameter is returned to Successcallback or Errorcallback return
        response
    })
})
Example 1Before the curd example has a user experience is not very good, users in the use of some features if the network is slow, the screen does not give feedback, the user is not aware of his operation is successful or failed, he does not know whether to continue to wait.
Through Inteceptor, we can add a loading for all request processing: show loading before sending, and hide loading after receiving response.
The specific steps are as follows:
1. Add a loading component
<template id= "Loading-template" >
    <div class= "Loading-overlay" >
        <div class= "Sk-three-bounce" ">
            <div class=" Sk-child sk-bounce1 "></div>
            <div class=" Sk-child sk-bounce2 "></div >
            <div class= "Sk-child sk-bounce3" ></div>
        </div>
    </div>
</template >
2. Loading component as a subassembly of another Vue instance
var help = new Vue ({
    el: ' #help ',
    data: {
        showloading:false
    },
    components: {
        ' loading ': {
            Template: ' #loading-template ',}}
)
3. Mount the Vue instance to an HTML element
<div id= "Help" >
    <loading v-show= "showloading" ></loading>
</div>
4. Add Inteceptor
Vue.http.interceptors.push (Request, Next) => {
    Loading.show = True
    Next (response) => {
        Loading.show = False return
        response
    });
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/inteceptor-demo1.html Example 2When the user stays on the screen for too long, the screen data may not be the latest, then if the user deletes or modifies a piece of data, if this data has been deleted by other users, the server will feedback a 404 error, However, because our put and delete requests do not handle errorcallback, users do not know whether or not his operation was successful or failed.
You ask me why do not handle errorcallback in each request, this is because I am lazy. This problem can also be solved by inteceptor.
1. Continue with the above loading component, add a dialog box under the #help element
<div id= "Help" >
    <loading v-show= "showloading" ></loading>
    <modal-dialog:show= " ShowDialog ">
        
2. Add two properties to the data option for the Help instance
var help = new Vue ({
        el: ' #help ',
        data: {
            showloading:false,
            showdialog:false,
            errorcode: "
        },
        components: {
            ' loading ': {
                Template: ' #loading-template ',
    }}}
3. Modify Inteceptor
Vue.http.interceptors.push (Request, Next) => {
    help.showloading = True
    Next (response) => {
        if (!) Response.ok) {
            Help.errorcode = response.status
            Help.showdialog = True
        }
        help.showloading = False Return
        response
    });
Demo Address: http://211.149.193.19:8090/vue-tutorials/03.Ajax/vue-resource/inteceptor-demo2.html
Reprint Address: http://www.cnblogs.com/keepfool/p/5657065.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.