1. Front – end interaction mode

1.1 Interface Invocation Mode P508

  • Native ajax
  • Jquery-based Ajax
  • fetch
  • axios

1.2 Url Address Format

1. Traditional urls Restful URL

Const app = express() const bodyParser = require('body-parser') // Handle static resources App.use (express.static('public')) // Handle app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); All ('*', function (req, res, next) {res.header(" access-Control-allow-origin ", "*"); res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Headers', 'mytoken'); next(); }); app.get('/async1', (req, res) => { res.send('hello1') }) app.get('/async2', (req, res) => { if(req.query.info == 'hello') { res.send('world') }else{ res.send('error') } }) app.get('/adata', (req, res) => { res.send('Hello axios! ('/')}) app. Get axios', (the req, res) = > {res. Send (' axios get pass parameters' + the req. Query. Id)}) app. Get ('/axios: id, (the req, Res) => {res.send('axios get (Restful) '+ req.params.id)}) app.delete('/axios', (req, Res) => {res.send('axios get '+ req.query.id)}) app.post('/axios', (req, Res) = > {res. Send (' axios post passing parameters' + the req. Body. The uname + + the req. '-' body. The PWD)}) app. Put ('/axios: id, (the req, Res) = > {res. Send (' axios put pass parameters' + the req. Params. Id + + the req. '-' body. The uname + + the req. '-' body. The PWD)}) app.get('/axios-json', (req, res) => { res.json({ uname: 'lisi', age: 12 }); }) app.get('/fdata', (req, res) => { res.send('Hello Fetch! ('/')}) app. Get books', (the req, res) = > {res. Send (' traditional URL parameter. '+ req.query.id)}) app.get('/books/:id', (req, res) => {res.send('Restful URL sends parameters! '+ req.params.id)}) app.delete('/books/:id', (req, res) => {res.send(' delete request to pass parameters! '+ req.params.id)}) app.post('/books', (req, res) => {res.send(' post request to send parameters! '+ the req. Body. Uname +' - '+ the req. Body. PWD)}) app. Put ('/books / : id, (the req, res) = > {res. Send (' passing arguments put request! ' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) }) app.get('/json', (req, res) => { res.json({ uname: 'lisi', age: 13, gender: 'male' }); }) app.get('/a1', (req, res) => { setTimeout(function(){ res.send('Hello TOM! ')}, 1000); }) app.get('/a2', (req, res) => { setTimeout(function(){ res.send('Hello JERRY! ')}, 2000); }) app.get('/a3', (req, res) => { setTimeout(function(){ res.send('Hello SPIKE! ')}, 3000); }) / / routing app. Get ('/data '(the req, res) = > {res. Send (' Hello World! ') }) app.get('/data1', (req, res) => { setTimeout(function(){ res.send('Hello TOM! ')}, 1000); }) app.get('/data2', (req, res) => { res.send('Hello JERRY! ')}) / / start to monitor app. Listen (3000, () = > {the console. The log (' running... ')})Copy the code

2. I Promise I can’t do it

2.1 Asynchronous Invocation

  • JavaScript execution environment is “single threaded”

  • The so-called single thread refers to that there is only one thread in the JS engine responsible for interpreting and executing JavaScript code, that is, only one task can be completed at a time, and the next task can be executed after the completion of this task, which will “block” other tasks. This task can be called the main thread

  • Asynchronous mode can perform multiple tasks together

  • JS common asynchronous calls

    • Timing task
    • ajax
    • Event functions
  • Dependency analysis for multiple asynchronous calls

    • Multiple asynchronous calls result in an uncertain order
    • The result of an asynchronous call needs to be nested if there are dependencies
<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div> <script type="text/javascript" SRC ="js/jquery.js"></script> <script type="text/javascript"> /* Front-end interaction - Asynchronous programming and Promise overview */ // var ret = '---'; // $.ajax({ // url: 'http://localhost:3000/data', // success: function(data) { // ret = data; // console.log(ret) // } // }); / / the console. The log (ret) / / -- -- -- -- -- -- -- -- -- -- -- -- the result of multiple asynchronous invocation order not sure -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / $. Ajax ({/ / url: 'http://localhost:3000/data', // success: function(data) { // console.log(data) // } // }); // $.ajax({ // url: 'http://localhost:3000/data1', // success: function(data) { // console.log(data) // } // }); // $.ajax({ // url: 'http://localhost:3000/data2', // success: function(data) { // console.log(data) // } // }); / / -- -- -- -- -- -- -- -- -- if there is a dependence of the results of the asynchronous call, will need to be nested -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - $. Ajax ({url: 'http://localhost:3000/data' success: function(data) { console.log(data) $.ajax({ url: 'http://localhost:3000/data1', success: function(data) { console.log(data) $.ajax({ url: 'http://localhost:3000/data2', success: function(data) { console.log(data) } }); }}); }}); </script> </body> </html>Copy the code

2.2 summary of promise

  • Syntactically, a promise is an object from which to get messages for asynchronous operations

  • Mainly solve the problem of asynchronous deep nesting

  • Promise provides a concise API to make asynchronous operations easier

2.3 Basic usage of PROMISE P510

  • instantiationpromiseObject, the transfer function in the constructor used to handle asynchronous tasks
  • resolveandrejectTwo parameters the user handles both success and failure and passesp.thenObtaining processing results
<script type="text/javascript"> /* 1. Promise basic use We use new to build a Promise. The constructor of a Promise takes one argument, which is a function, and passes in two arguments: */ var p = new Promise(function(resolve, reject){//2. SetTimeout setTimeout(function(){var flag = false; If (flag) {//3. Resolve ('hello'); }else{//4. Reject (' something wrong '); }}, 100); }); When a Promise instance is generated, you can use the then method to specify resolved and reject callbacks. P.teng (function(data){console.log(data)},function(info){console.log(info)}); </script>Copy the code

2.4 Send Ajax request P511 based on Promise

<script type="text/javascript"> /* Send Ajax requests based on promises */ function queryData(URL) {# 1.1 create a Promise instance var p = new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ! = 4) return; Resolve (xhr.responsetext); if(xhr.readyState == 4 &&xhr.status == 200) {# 1.2 resolve(xhr.responsetext); }else{# 1.3 reject(' server error '); }}; xhr.open('get', url); xhr.send(null); }); return p; } //------- send multiple Ajax requests in order ------------- # note: In the then method, you can also return data directly instead of a Promise object, In the back of the then can receive data queryData (' http://localhost:3000/data '). Then (function (data) {the console. The log (data) # 1.4 want to continue the chain programming Need to be return return queryData('http://localhost:3000/data1'); }) .then(function(data){ console.log(data); return queryData('http://localhost:3000/data2'); }) .then(function(data){ console.log(data) }); </script>Copy the code

The return value p512 in the then argument

1. Return the Promise instance object

  • The returned instance object calls the next THEN
  • The result of the previous asynchronous task can be obtained in the next THEN

2. Return a common value

  • The normal value returned is passed directly to the next THEN, which is received by the argument of the function in the THEN argument
  • A promise instance object is generated by default to ensure that the next THEN can be chained
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script Function queryData(url) {return new Promise(function(resolve, resolve)); reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ! = 4) return; Resolve (xhr.responsetext); if(xhr.readyState == 4 &&xhr.status == 200) {resolve(xhr.responsetext); }else{// Handle exceptions reject(' server error '); }}; xhr.open('get', url); xhr.send(null); }); } queryData('http://localhost:3000/data') .then(function(data){ return queryData('http://localhost:3000/data1'); }) .then(function(data){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(123); }, 1000)}); }) //.then(function(data){ // console.log(data) //}) //123 .then(function(data){ return 'hello'; }) .then(function(data){ console.log(data) }) //hello </script> </body> </html>Copy the code

2.6 API P513 commonly used for Promise

1. Instance method

  • .then() gets the correct result of the asynchronous task
  • .catch() gets the exception information
  • .finally() Success or failure is executed (not a formal criterion)
<script type="text/javascript"> /* Promise function foo() { return new Promise(function(resolve, reject){ setTimeout(function(){ // resolve(123); reject('error'); }, 100); }) } // foo() // .then(function(data){ // console.log(data) // }) // .catch(function(data){ // console.log(data) // }) // .finally(function(){ // console.log('finished') // }); / / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / two writing is the equivalent of foo (). Then (function (data) {# asynchronous tasks right results the console. The log (data)}, function (data) { Console.log (data)}) finally(function(){console.log('finished')}); </script>Copy the code

2. Object method p514

  • .all()

    • When multiple asynchronous tasks are processed concurrently, the result can be obtained only when all tasks are completed
    • Promise.allMethod takes an array of objects (P1, P2, p3) that are instances of a Promise. (If it is not a Promise, the item will be used.Promise.resolveConvert to a promise). Its state is determined by the three promise instances
  • .race()

    • Processing multiple asynchronous tasks concurrently, as long as one task is completed, the results can be obtained
    • Promise.raceThe method also takes an array as an argument. When the state of one instance in P1, P2, p3 changes (becomesfulfilledorrejected), and the state of P changes accordingly. And pass the return value of the first promise that changed the state to p’s callback
<script type="text/javascript"> /* Promise common API- object method */ // console.dir(Promise) function queryData(URL) {return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState ! = 4) return; Resolve (xhr.responsetext); if(xhr.readyState == 4 &&xhr.status == 200) {resolve(xhr.responsetext); }else{// Handle exceptions reject(' server error '); }}; xhr.open('get', url); xhr.send(null); }); } var p1 = queryData('http://localhost:3000/a1'); var p2 = queryData('http://localhost:3000/a2'); var p3 = queryData('http://localhost:3000/a3'); All ([p1,p2,p3]). Then (function(result){// all = "HELLO TOM", "HELLO JERRY" "HELLO SPIKE"] console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]}) Promise. Race ([p1,p2,p3]). Then (function(result){// If p1 is executed faster, then() will get result 'p1'. P2,p3 continue to execute, but the execution results will be discarded. console.log(result) // "HELLO TOM" }) </script>Copy the code

3. Interface call -fetch usage

3.1 Fetch Overview P516

1. Basic features

  • A simpler way to get data, with more power and flexibility, can be seen as an upgrade to XHR

  • Implementation based on promises

  • Fetch is not a further encapsulation of Ajax, but rather native JS, without using XMLHttpRequest objects.

  • The fetch (url, options). Then ()

2. Grammatical structure

3.2 Basic usage of FETCH

<script type="text/javascript"> /* Fetch API basic usage Fetch (URL).then() the first parameter of the request path Fetch will return a Promise so we can use then to get the result of the successful request */ Fetch (' http://localhost:3000/fdata '). Then (function (data) {/ / text () method to a part of the fetchAPI, it returns a Promise instance objects, Return data.text(); }). Then (function(data){console.log(data); }) </script>Copy the code

3.3 Fetch Request Parameter P516

1. Common configuration options

  • Method (string) : HTTP request method. Default is GET (POST, GET, DELETE, UPDATE, PATCH, and PUT).

  • Body (string)) : HTTP request parameter

  • Headers (object) : HTTP request header, default {}

2. Parameter transfer in get request mode

  • ? id /id

3. Delete Parameter transfer in request mode

  • /id

4. Parameter transfer in POST request mode

  • Set the body and headers

5. Put Parameter transfer in request mode

  • Generally used to modify data

The server side

App.get ('/books', (req, res) => {res.send(' traditional URL pass parameters! '+ req.query.id)}) app.get('/books/:id', (req, res) => {res.send('Restful URL sends parameters! '+ req.params.id)}) app.delete('/books/:id', (req, res) => {res.send(' delete request to pass parameters! '+ req.params.id)}) app.post('/books', (req, res) => {res.send(' post request to send parameters! '+ the req. Body. Uname +' - '+ the req. Body. PWD)}) app. Put ('/books / : id, (the req, res) = > {res. Send (' passing arguments put request! ' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd) })Copy the code

The client

<script type="text/javascript"> /* Fetch API call interface pass parameter */ #1.1 GET parameter pass - traditional URL through the URL? In the form of spread and the fetch (' http://localhost:3000/books? Id =123', {# get request can be omitted without writing the default is get method: 'get'}). Then (function(data) {# return data.text(); }). Then (function(data) {# console.log(data)}); # 1.2 the GET parameter passing in the form of a restful URL in the form of pass/passing parameters Id = 456 and configuration id the background about the fetch (' http://localhost:3000/books/456 ', }). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) }); Way # 2.1 the DELETE request parameter passing DELETE id is the id = 789 the fetch (' http://localhost:3000/books/789 '{method: 'delete' }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # 3.1 transmit the POST request parameter (string format) the fetch (' http://localhost:3000/books' {method: "POST", # 3.1 pass data body: 'uname=lisi&pwd=123', # 3.2 Headers: {' content-type ': 'application/x-www-form-urlencoded' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # 3.2 POST request parameter (json format) the fetch (' http://localhost:3000/books' {method: "POST", the body: json. Stringify ({uname: 'Joe Smith, PWD: '456' }), headers: { 'Content-Type': 'application/json' } }) .then(function(data) { return data.text(); }).then(function(data) { console.log(data) }); # 4. Transmit and modify the PUT request id is 123, fetch (' http://localhost:3000/books/123 '{method:' PUT 'body: JSON. The stringify ({uname: }}). Then (function(data) {return data.text(); }).then(function(data) { console.log(data) }); </script>Copy the code

3.4 Fetch Response result P518

Fetch is used to fetch data. If the response is returned normally, the first thing we see is a Response object, which includes a bunch of returned original bytes. After receiving these bytes, we need to call methods to convert them into data in corresponding formats, such as JSON, BLOB or TEXT

Response data format

  • Text () : Treats the return body as a string
  • Json () : Returns the same result as json.parse(responseText)

The client

/ * response results of the Fetch data formats * / Fetch (' http://localhost:3000/json '). Then (function (data) {/ / return data. The json (); Return data.text(); return data.text(); // // convert data to string}). Then (function(data){// console.log(data.uname) lisi // console.log(typeof data) var obj = JSON.parse(data); console.log(obj.uname,obj.age,obj.gender) })Copy the code

The server side

app.get('/json', (req, res) => {
  res.json({
    uname: 'lisi',
    age: 13,
    gender: 'male'
  });
})
Copy the code

4. Interface call-AXIos usage

4.1 AxiOS basic featureswebsite p519

  • HTTP client based on Promise for browsers and Node.js
  • Supports browsers and Node.js
  • Supporting promise
  • Intercepts requests and responses
  • Automatically convert JSON data
  • Ability to transform request and response data

4.2 Basic usage of axios

<script type="text/javascript" src="js/axios.js"></script> <script type="text/javascript"> Axios. Get (' http://localhost:3000/adata '). Then (function (ret) {/ / pay attention to the usage data attribute is fixed, Log (ret. Data) console.log(ret)}) </script>Copy the code

4.3 Axios common API P520

  • get(Query data) anddelete(delete data) Request pass parameters
    • Through the traditional URL with? Pass parameters in the form ofreq.query.id
    • Restful/Passes parametersreq.paramas.id
    • Pass parameters through paramsreq.query.id

  • post(Add data) andput(Modify data) Request pass parameter P520
    • Pass parameters through options (the default is passedjson{uname:”zhangsan”, PWD :12345})req.body.uname

    • Pass parameters through URLSearchParams (application/x-www-form-urlencoded– the uname = zhangsan&pwd = 12345)req.body.uname

The server side

App.get ('/axios', (req, res) => {res.send('axios get '+ req.query.id)}) app.get('/axios/:id', (req, Res) => {res.send('axios get (Restful) '+ req.params.id)}) app.delete('/axios', (req, Res) => {res.send('axios get '+ req.query.id)}) app.post('/axios', (req, Res) = > {res. Send (' axios post passing parameters' + the req. Body. The uname + + the req. '-' body. The PWD)}) app. Put ('/axios: id, (the req, Res) = > {res. Send (' axios put pass parameters' + the req. Params. Id + + the req. '-' body. The uname + + the req. '-' body. The PWD)})Copy the code

The client

# 1. Send a get request axios. Get (' http://localhost:3000/adata '). Then (function (ret) {# get ret is an object All objects within the data property of ret / / // console.log(ret. Data) console.log(ret)}) # 2. In the form of passing parameters axios. Get (' http://localhost:3000/axios? Id =123'). Then (function(ret){console.log(ret. Data)}) # 2.2 restful Axios. Get (' http://localhost:3000/axios/123 '). Then (function (ret) {the console. The log (ret) data)}) # 2.3 through the params form passing parameters axios.get('http://localhost:3000/axios', { params: { id: 789}}). Then (function(ret){console.log(ret. Data)}) #3 AXIos delete requests pass parameters in the same form as get requests axios.delete('http://localhost:3000/axios', { params: { id: 111}}).then(function(ret){console.log(ret. Data)}) # 4 Axios post request # 4.1 pass parameters through options axios.post('http://localhost:3000/axios', { uname: 'lisi', pwd: Var params = new URLSearchParams(); params.append('uname', 'zhangsan'); params.append('pwd', '111'); axios.post('http://localhost:3000/axios', Params).then(function(ret){console.log(ret. Data)} axios.put('http://localhost:3000/axios/123', { uname: 'lisi', pwd: 123 }).then(function(ret){ console.log(ret.data) })Copy the code

4.4 Axios response result P522

The main properties of the response result

  • Data: indicates the actual response data
  • Headers: information about the response header
  • Status: indicates the response status code
  • StatusText: indicates the response status
/ / the server app. Get ('/axios - json, (the req, res) = > {res. Json ({uname: 'lisi, age: 12}); }) / / client axios. Get (' http://localhost:3000/axios-json '). Then (function (ret) {the console. The log (ret) data) uname) / / lisi})Copy the code

4.5 AxiOS Global Configuration

Axios.defaults. baseURL = 'HTTPS :/localhost:300/'; Axios.defaults. timeout = 2500; # configuration public request header axios.defaults.headers.com mon [' Authorization '] = AUTH_TOKEN; # configuration of public post the content-type axios. Defaults. Headers. Post [' the content-type '] = 'application/x - WWW - form - urlencoded'; axios.get('axios-json').then(function(ret){ console.log(ret.data.uname)//lisi })Copy the code

4.6 AXIos interceptor P522

1. Request interceptor

  • The purpose of a request interceptor is to do something before a request is sent
  • For example, add token to each request body, which makes it easy to change later

2. Response interceptor

  • The purpose of a response interceptor is to do something after receiving a response
  • For example, if the server login status is invalid and you need to log in to the server again, the login page is displayed

# 1. Request interceptor axios. Interceptors. Request. Use (function (config) {the console. The log (config. Url) # 1.1 any request after this step Before sending a request do config.headers.mytoken = 'nihao'; Return config; }, function(err){#1.3 do something about the error console.log(err)}) #2. Response interceptor axios. Interceptors. Response. Use (function (res) {# 2.1 in receiving the response do var data = res. The data; return data; }, function(err){#2.2 do something about response error console.log(err)})Copy the code

5. Interface call -async/await usage p524

  • Asycn /await is a new syntax introduced in ES7 to make it easier to operate asynchronously and make asynchronous code look and behave more like synchronous code

  • Async precedes functions as a keyword

    • Any async function implicitly returns a promise
  • The await keyword can only be used in functions defined using async

    • Await can get asynchronous results
    • Await can be followed directly by a Promise instance object
    • The await function cannot be used alone

The server side

app.get('/async1', (req, res) => {
  res.send('hello1')
})
app.get('/async2', (req, res) => {
  if(req.query.info == 'hello') {
    res.send('world')
  }else{
    res.send('error')
  }
})
Copy the code

The client

/* async/await async operations: Async functions return an await Promise instance object and can be followed directly by a Promise instance object */ # 1 QueryData () {# 1.2 await keyword can only be used in functions defined using async to await an instance of a Promise object var ret = await new Promise(function(resolve, resolve, resolve) reject){ setTimeout(function(){ resolve('nihao') },1000); }) // console.log(ret.data) return ret; } #2. Then (function(data){console.log(data) // nihao}) #2. Async functions handle multiple asynchronous functions axios.defaults.baseURL = 'http://localhost:3000'; Async function queryData() {# 2.1} var info = await axios.get('async1'); Var ret = await axios.get('async2? info=' + info.data); return ret.data; } queryData().then(function(data){ console.log(data) })Copy the code

6. Library Case P526

Reconstruction based on background interface

Library management background interface document

Base path: http://localhost:3000/

GET book list data GET

  • Path: books
  • Request parameters: None
  • In response to the results
[{" id ":" 4 ", "name" : "a dream of red mansions", "date" : 2525609975000}, {" name ":" the romance of The Three Kingdoms ", "date" : 2525609975000, "id" : 5}, {" name ": "Water margin", "date" : 2525609975000, the "id" : 6}, {" name ":" journey to the west ", "date" : 2525609975000, "id" : 7}]Copy the code

Add Book – Submit book information POST

  • Path: books
  • Request parameters
    • Name: indicates the book name
  • In response to the results
{"status": 200 (200 indicates success; 500 means failure)}Copy the code

Edit books – Query book information by ID GET

  • Path: books / : id
  • Request parameters: None
  • In response to the results
{"name":" journey to the West ", "date":2525609975000, "id":7}Copy the code

Edit book – Submit book information PUT

  • Path: books / : id
  • Request parameters
    • Name: indicates the book name
  • In response to the results
{"status": 200 (200 indicates success; 500 means failure)}Copy the code

DELETE book information DELETE

  • Path: books / : id
  • Request parameters: None
  • In response to the results
{"status": 200 (200 indicates success; 500 means failure)}Copy the code

Verify that the book name has a GET

  • Path: books/book / : name
  • Request parameters: None
  • In response to the results
{"status": 1 // (1 indicates existence; 2: does not exist)}Copy the code

1. Interface-based case – Get book list

  • Import AXIOS to send ajax
  • Render the obtained data onto the page
< div id = "app" > < div class = "grid" > < table > < thead > < tr > < th > id < / th > < th > name < / th > < th > time < / th > < th > action < / th > < / tr > < thead > <tbody> <! -- 5. Put the books in the data rendered to the page - > < tr: key = 'item. Id' v - for = 'item in books' > < td > {{item. Id}} < / td > < td > {{item. The name}} < / td > < td > {{item. Date}} < / td > < td > < a href = "" > change < / a > < span > | < / span > < a href =" "> delete < / a > < / td > < / tr > < / tbody > < / table > < / div > </div> <script type="text/javascript" src="js/vue.js"></script> 1. Import axios <script type="text/javascript" SRC ="js/axios.js"></script> <script type="text/javascript"> /* Library - Add books */ # 2 Axios.defaults. baseURL = 'http://localhost:3000/'; / / configure response interceptor res - res. Data axios. Interceptors. Response. Use (function (res) {return res. Data; }, function(error) { console.log(error) }); var vm = new Vue({ el: '#app', data: { flag: false, submitFlag: false, id: '', name: '', books: [] }, methods: {# 3 define a method to send Ajax # 3.1 Use async to make asynchronous code write queryData synchronously: Async function() {var ret = await axios.get('books'); // this.books = ret.data; Get ('books'); this.books = await axios.get('books'); }}, mounted: function() {# 5 mounted: function() {this.queryData(); }}); </script>Copy the code

2 Add book P528

  • Get the data entered by the user and send it to the background
  • Render the latest data to the page
methods: { handle: Async function(){if(this.flag) {this.books.some((item) => {if(item.id == this.id) {if(item.id == this.id) { item.name = this.name; Return true; }}); this.flag = false; }else{# 1.1 Sending ajax requests in the previously wrapped Handle method # 1.2 Simplifying operations with async and await requires adding async var ret = await in front of function axios.post('books', { name: If (ret.status == 200) {this.queryData() {this.queryData(); }} // Clear the form this.id = "; this.name = ''; }},Copy the code

3 Verify that the book name contains P529

  • Send a request to verify that the schema already exists before adding the book
  • If not, add the book name to the background
    • You only need to change the value of submitFlag to check whether the book exists
watch: { name: Async function(val) {// var flag = this.books.some(function(item){// return item.name == val; / /}); var ret = await axios.get('/books/book/' + this.name); If (ret.status == 1) {// The book name exists this.submitFlag = true; }else{// Book name does not exist this.submitFlag = false; }}},Copy the code

4. Edit book P530

  • Query the book that you want to edit based on the current book ID
  • You need to determine whether to add or edit based on the status bits
methods: { handle: Var ret = await axios.put('books/' + this.id, {name: {name: {name: {}} this.name }); If (ret. Status == 200){#4.4 Reload list data this.queryData(); } this.flag = false; }else{// add books var ret = await axios.post('books', {name: This.name}) if(ret.status == 200) {// Reload list data this.queryData(); }} // Clear the form this.id = "; this.name = ''; }, toEdit: async function(id){#4.1 flag status bits used to distinguish between editing and adding operations this.flag = true; Var ret = await axios.get('books/' + id); this.id = ret.id; this.name = ret.name; },Copy the code

5 Delete book P531

  • The id books to be deleted are passed to the background in the form of parameters
DeleteBook: async function(id){var ret = await axios.delete('books/' + id); If (ret.status == 200) {// Reload list data this.queryData(); }}Copy the code