In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how vue uses simulated json data to view the effect". In daily operation, I believe many people have doubts about how vue uses simulated json data to view the effect. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the question of "how vue uses simulated json data viewing effect". Next, please follow the editor to study!
Use simulated json data to view the effect
In the part of data interaction, we often have to communicate and cooperate with the background, as beginners or pure front-end learners, we can not often have the background to cooperate with ourselves to show, so how can we simulate a similar effect?
The value coming from the background is actually a kind of data in json format, and we only need to simulate the content in the form of json.
The specific methods are as follows
1) encapsulate a json file in which the required data is stored and placed in the common folder in the webpack environment.
The data are as follows:
{"name": "Zhang San", "age": 20, "phone": "12345678", "sex": "female", "grades": {"Chinese": 100,100 "Mathematics": 98, "English": 100,100 "computer": 95 Physics: 88, Circuits: 89}]}
2) reference the data of this data.json in the specified vue file
This example is order.vue
3) set the corresponding value in order.vue
Export default {name: 'Order', data () {return {name: ", age:0, phone:", sex: ", grades: [], avg:0}}
4) simulate the data and encapsulate it in created () to get the data you need.
Created () {this.name = data.name; this.age = data.age; this.phone = data.phone; this.sex = data.sex; this.grades = data.grades;}
5) Interface call
Name: {{name}} age: {{age}} phone: {{phone}} sex: {{sex}} vue simulation data, data interaction mock data
1. Define
Mock serve tool, in popular terms, is to simulate the interface data of the server. Generally speaking, after the front end is separated from the front end, the front-end staff can rely on API development to build a JSON service locally and generate their own test data. That is, json-server is a serve that stores json data.
Note: json-server supports CORS and JSONP cross-domain requests.
2.json-server
Steps to use:
Initialization project: npm init-y
Install json-server npm I json-server-D
Open project authoring data
Create a db.json in the root directory of the project and write legal json data.
Startup configuration
Add the following code under package.json:
"scripts": {"server": "json-server db.json"}
Running
Run on the command line: npm run server
$nextTick ()
1. Application scenario: when data updates affect the (new) dom, use $nextTick ().
Data interaction
1. Send an ajax request to the server to get the data.
two。 Solution
Encapsulate an ajax through a XMLHttpReauest object
Function ajax (options) {/ 1. Create the object var xhr = new XMLHttpRequest (); / / 2. Processing parameters-the parameters of the get request are in open, that is, concatenated after url, and the parameters of the post request are var params = formsParams (options.data) in send; / / 3. Determine the request mode if (options.type = = "GET") {xhr.open (options.type, options.url + "?" + params, options.async); xhr.send (null)} if (options.type = = "POST") {xhr.open (options.type, options.url, options.async) / / request header xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr.send (params);} / / 4. Set callback function xhr.onreadystatechange = function () {/ / xhr.readyState = = 4 request succeeded xhr.status = = 200Response completed if (xhr.readyState = = 4 & & xhr.status = = 200) {options.success (xhr.responseText);}} function formsParams (data) {var arr = [] For (var key in data) {/ / separates the string with =, then inserts the value into the arr array / / key is the key of the object, and data [key] is the value arr.push corresponding to the key (key+ "=" + data [key]);} return arr.join ("&") }} ajax ({url: "address", / / url---- > address type: "POST", / / type-- > request method async: true, / / async---- > synchronization: false Async: true data: {/ / incoming information name: "Zhang San", age: 18}, success: function (data) {/ / return acceptance information console.log (data) })
Use the ajax library that comes with a third party. (jquery)
Steps to use:
1. In the .vue file, jquery is introduced outside the script tag.
Import $from "jquery"
two。 Just send the request directly. Pay attention to the timing of sending requests.
New fetch for ES6
Format: fetch (String url, configuration), which returns a Promise object.
Fetch (url, {method: headers: body://body: request body information, which may be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that requests for GET or HEAD methods cannot contain body information. }) / / fetch (url?id=001, {method:'GET'}) in get mode. Then (response = > response.json ()) / / response.json () the data returned by the backend Convert to json format .then (data = > console.log (data)) .catch (e = > console.log ("Oops, error", e)) / / post fetch (url, {method: "POST", headers: new Headers ({'Content-Type':' application/x-www-form-urlencoded' / / specify form submission}) Body: "id=001&name= Zhang Sanlian" / / parameters of the post request}) .then (response = > response.json ()) .then (data = > console.log (data)) .catch (e = > console.log ("Oops, error", e)
Features:
1.fetch request does not have cookie by default. You need to set fetch (url, {credentials:'include'}).
two。 When the server returns a 400500 error code, it will not reject. Only if the request cannot be completed due to a network error, the fetch will be reject.
Libraries encapsulated into promise habits using third-party ajax.
1. Definition:
A third-party library based on promise that can be used in browsers (front end) and nodej.js (back end).
two。 Format
Axios ({url: "address" method: "submit method" params: {} data carried by address bar (get mode) data: {} non-address bar carries data (such as: post,put, etc.), baseURL: if url is not an absolute address, it will be added in front of it. This setting is very convenient when axios uses relative addresses}) .then (res= > {console.log (res.data);})
Full format of axios and aliases for axios (get and post)
Axios ({configuration}) .then (successful callback (res). Catch (failed callback (res))
Axios.get (url, {configuration}) .then (successful callback (res)) .catch (failed callback (res))
Axios.post (url, {configuration}) .then (successful callback (res)) .catch (failed callback (res))
Note: the response body, the data is inside the res.data.
Eg:get request
Axios ({url:'getGoodsListNew.php', / / method:'get', defaults to get request params: {count:3}}) .then (res= > this.goodslist=res.data)
Eg:post request
1) data is a string
When data is a string, the content-type in the request header is the data type seen in application/x-www-form-urlencoded,network: formData.
Axios ({method:'post', url:'regSave.php', data:'username=jzmdd&userpass=123'}) .then (res= > {… });
2) data is a URLSearchParams object
When data is a URLSearchParams object, the same data is a string.
Var params = new URLSearchParams (); params.append ('username', Zhang Sanlian); params.append (' userpass', '123'); axios ({method:'post', url:'regSave.php', data:params}). Then (res= > {… });
3) data is a json object
When data is a json object, the content-type in the request header is the data type seen in application/json,network: request payload.
Axios ({url: "/ vips", method: "post", data: {name:this.name, pass:this.pass, sex:this.sex}, baseURL: "http://localhost:3000"}) .then (res= > console.log (res.data))
3. [interview] the difference between Ajax,jQuery ajax,axios and fetch
Ajax is the earliest front-end interaction technology, is the native js, the core is the use of XMLHttpRequest objects, if there is a relationship between multiple requests, there will be callback hell. (using promise to solve the problem) fetch is added by ES6 and fetch is designed based on promise. Fetch is not a further encapsulation of ajax, but a native js. The fetch function is the native js and does not use the XMLHttpRequest object.
JQuery ajax is the encapsulation of native ajax; axios is the encapsulation of native ajax, based on promise objects. Axios can also intercept during the request and response phases. It can be used not only on the client side, but also on the node.js side.
At this point, the study on "how vue uses simulated json data to view the effect" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.