Vue2+vuerouter2+webpack construction Project Combat (IV): Connect API, Render list

Source: Internet
Author: User

Through the previous tutorials, we have successfully set up, and have set up a good route. In this section, we need to make a list page and then render it using the public API that gets http://cnodejs.org/api.

We open the Src/page/index.vue file and write the following code here:

<Template>  <Div>    <H1class= "logo">Cnodejs Api Test</H1>    <ulclass= "List">      <Liv-for= "Item in lists"V-text= "Item.title"></Li>    </ul>  </Div></Template><Script>Exportdefault{data () {return{lists:[{ID:1, Title:"Test Title 1"},{ID:2, Title:"Test Title 2"      }]    }  }}</Script>

Through the browser, we can see the result of rendering:

Use Scss to write styles

New file, Src/style/scss/_index.scss

Then enter the SRC/STYLE/STYLE.SCSS in the

@import "Scss/index";

Then we can see the list of styles in the browser, as follows:

Note: My habit is that a file, a style, is located below the src/page/folder, and the style is under SRC/STYLE/SCSS. The file and style have the same name. If the file is in a subdirectory, such as Src/page/user/pay.vue, then the corresponding scss file is src/style/scss/user/_pay.scss.

Each team's specifications are not the same, are the strengths of each other, it is important that the organization.

Call Api.js

In the second section, we set up a api.js empty file under the Src/config directory. Not used in the third section. In this section, we're going to start using it.

First, we edit src/main.js, referencing Src/config/api.js. As follows:

Import API from './config/api '= API

Insert these two lines of code, the reference good api.js, and bind it to the global, then we can use this file in various places. Although this file is empty.

Then Src/main.js's complete code:

Import Vuefrom ' Vue './app'./config/routes.js 'false'./config/ Api.js '= APInew  Vue ({  ' #app ',  router,  ' <app/ > ', Components  : {App}})
Installing the Superagent Component

To request an interface, you must have a corresponding component. If you've ever used jquery, you should be familiar with the AJAX approach. Of course, in Vue, we don't consider using jquery. We use the superagent component.

Installation is very simple, we first jump to the project root directory, npm install superagent -D and then enter to install.

Writing api.js files

With the tools, we need to write the Api.js file so that it can do the work we want.

//Configure API Interface addressvarroot = ' Https://cnodejs.org/api/v1 ';//Reference superagentvarRequest = require (' superagent ');//Custom Judgment element type JSfunctionToType (obj) {return({}). Tostring.call (obj). Match (/\s ([a-za-z]+)/) [1].tolowercase ()}//parameter filter functionfunctionfilter_null (o) { for(varKeyincho) {if(O[key] = =NULL) {      DeleteO[key]}if(ToType (O[key]) = = ' String ') {O[key]=O[key].trim ()if(O[key].length = = 0) {        DeleteO[key]}} }  returnO}/*Interface Handler function This function is different for each project, I am now adjusting the interface for HTTPS://CNODEJS.ORG/API/V1, if other interfaces need to be adjusted according to the parameters of the interface. Reference Document address: HTTPS://CNODEJS.ORG/TOPIC/5378720ED6E2D16149FA16BD*/function_api_base (method, URL, params, success, failure) {varR = Request (method, URL). Type (' Text/plain ')  if(params) {params=filter_null (params); if(method = = = ' POST ' | | method = = = ' PUT ')) {      if(ToType (params) = = ' object ') {params=json.stringify (params); } R=r.send (params)}Else if(method = = ' GET ' | | method = = = ' DELETE ') {R=r.query (params)}} R.end (function(Err, res) {if(ERR) {alert (' API error, HTTP CODE: ' +res.status); return;    }; if(Res.body.success = =true) {      if(Success) {success (res.body); }    } Else {      if(failure) {failure (res.body); } Else{alert (' ERROR: ' +json.stringify (res.body)); }    }  });};//returns the calling interface in the Vue templateExportdefault{get:function(URL, params, success, failure) {return_api_base (' GET ', root + '/' +URL, params, success, Failure)}, Post:function(URL, params, success, failure) {return_api_base (' POST ', root + '/' +URL, params, success, Failure)}, put:function(URL, params, success, failure) {return_api_base (' PUT ', root + '/' +URL, params, success, Failure)},Delete:function(URL, params, success, failure) {return_api_base (' DELETE ', root + '/' +URL, params, success, Failure)},}

This file is a bit of a cool hang-fried sky. At present, we test cnodejs.org interface, I adjust to be able to use. In fact, in other interface projects, this is something that needs to be adjusted to fit the code to your project. Mainly based on the content returned by the interface to make a variety of judgments and processing, where the main framework code is not moving.

Calling API interface in templates try

Edit the Src/page/index.vue file with the following code:

<Template>  <Div>    <H1class= "logo">Cnodejs Api Test</H1>    <ulclass= "List">      <Liv-for= "Item in lists"V-text= "Item.title"></Li>    </ul>  </Div></Template><Script>Exportdefault{data () {return{lists:[]}}, created () {//after the component is created, get the data, which is not the same as 1.0, changed to this way     This. Get_data ()}, methods: {get_data:function(params) {varv=  This      if (!params) params= {}      //we use the global binding $api method to get the data, convenient ~v. $api. Get ('Topics', params,function(r) {v.lists=r.data})},}, }</Script>

Once saved, we can see the rendered list in the browser. As shown in the following:

Reference

Reference Address: http://blog.csdn.net/fungleo/article/details/53202276

Vue2+vuerouter2+webpack construction Project Combat (IV): Connect API, Render list

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.