Vue2+VueRouter 2+webpack Construction Project (4) Connect the api and render a list first

Keywords: Vue Webpack JQuery JSON

Vue2+VueRouter 2+webpack Construction Project (4) Connect the api and render a list first

Catalog Index

"Vue2 + VueRouter 2 + webpack construction project actual combat (1) preparation work"

"Vue2 + VueRouter 2 + webpack Construction Project Actual Warfare (II) Directory and File Structure"

"Vue2+VueRouter 2+webpack Construction Project (3) Configuration Routing, Two Pages First"

"Vue2 + VueRouter 2 + webpack construction project (4) Connect api, render a list first"

"Vue2+VueRouter 2+webpack Construction Project (V) Configuration Subrouting"

Through the previous tutorials, we have successfully set up the routing, and have already set up the routing. In this chapter, we need to make a list page, and then use the access. http://cnodejs.org/api The public API is rendered.

Make a list page

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

<template>
  <div>
    <h1 class="logo">cnodejs Api Test</h1>
    <ul class="list">
      <li v-for="item in lists" v-text="item.title"></li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      lists:[{
        id:1,
        title:"test title 1"
      },{
        id:2,
        title:"test title 2"
      }]
    }
  }
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

As mentioned above, we can easily render the page successfully through two sets of data we have written. Through the browser, we can see the effect.

Matching point css

Here, what I emphasize is not how to write css, but the structure of my organizational project. I feel that my organization is still very good.

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

Enter the following

.logo {color: red;}
.list {
  line-height: 2;
  li {border-bottom: 1px solid #ddd;}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Then enter it in src/style/style.scss

@import "scss/index";
  • 1
  • 1

Then we can see the styled list in the browser.

My habit is, a file, a style, the file is under the Src / page / folder, the style is under the Src / style / scss. Documents and styles have the same name. If the file is located in a subdirectory, such as src/page/user/pay.vue, then the corresponding SCSS file is src/style/scss/user/_pay.scss.

The norms of each team are different, each has its own strengths, and the important thing is to be organized.

Call api.js

In the second section, we created an empty api.js file under the src/config directory. It is not used in Section 3. In this section, we'll start using it.

First, we edit src/main.js and refer to src/config/api.js. As follows:

import api from './config/api'
Vue.prototype.$api = api
  • 1
  • 2
  • 1
  • 2

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

Maybe some friends don't know where to insert the file. I put all the code of main.js here:

// There's nothing to say about quoting vue
import Vue from 'vue'
// Referenced routing
import VueRouter from 'vue-router'
// You can't just quote it, you have to use it.
Vue.use(VueRouter)
// The entry file is src/App.vue file, so you need to refer to it
import App from './App.vue'
// Reference Routing Profile
import routes from './config/routes'
// Reference to API files
import api from './config/api'
// Binding API methods to global
Vue.prototype.$api = api
// Using configuration file rules
const router = new VueRouter({
  routes
})
// Run up.
new Vue({
  router,
  el: '#app',
  render: (h) => h(App)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

Install superagent components

To request an interface, there must be corresponding components. If you have used it jQuery You should be familiar with the AJAX method. Of course, in vue, we don't consider using jquery. We use the component superagent.

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

Write api.js file

With tools, we need to write api.js files so that it can do what we want.

// Configure API interface address
var root = 'https://cnodejs.org/api/v1';
// Reference to superagent
var request = require('superagent');
// Custom Judgment Element Type JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// Parametric filtering function
function filter_null(o) {
  for (var key in o) {
    if (o[key] == null) {
      delete o[key]
    }
    if (toType(o[key]) == 'string') {
      o[key] = o[key].trim()
      if (o[key].length == 0) {
        delete o[key]
      }
    }
  }
  return o
}
/*
  Interface Processing Function
  This function is different for each item, and what I'm adjusting now is to apply it to
  https://cnodejs.org/api/v1 Interfaces, if any
  It needs to be adjusted according to the parameters of the interface. Reference Note Document Address:
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
*/
function _api_base(method, url, params, success, failure) {
  var r = 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 call interface in the vue template
export default {
  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)
  },
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76

This document is a bit crazy and dazzling. At present, we test The interface of cnodejs.org, which I adjusted to be usable. In fact, in other interface projects, this needs to be adjusted to the appropriate code for your project. Mainly based on the content returned by the interface for various judgments and processing, the main framework code is not active.

If your JS foundation is too hard, you can understand it at a glance. If you can't, take your time and understand it slowly. Anyway, I can't base on it, and I understand it.

Try calling api interface in template

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

<template>
  <div>
    <h1 class="logo">cnodejs Api Test</h1>
    <ul class="list">
      <li v-for="item in lists" v-text="item.title"></li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      lists:[]
    }
  },
  created () {
    // After the component is created, the data is retrieved, which is different from 1.0. This is what it looks like.
    this.get_data()
  },
  methods: {
    get_data: function(params) {
      var v = this
      if (!params) params = {}
      // Let's use the $api method of global binding to get the data. It's convenient.~
      v.$api.get('topics', params, function(r) {
        v.lists = r.data
      })
    },
  },
}
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

After saving, we can see the rendered list in the browser. As shown in the following figure:

Summary

Well, through this section, we have successfully obtained the data from the interface and rendered it into our pages. This has actually solved most of the problems.

  1. How to create a new js file, reference it, and bind it to the global
  2. Learn to understand superagent plug-ins.
  3. How to call the bound method in the vue template.
  4. When the component rendering is complete, the function is executed.

My tutorial focuses on demonstrating how to link up and complete the various parts, not to do a perfect thing, so as long as the data can be read out, as for more content rendering, and a better style, not my business here. See my other blog posts.

This article was originally created by FungLeo and allowed to be reproduced, but reproduced must be accompanied by an initial link. If you don't have links, I will take measures including, but not limited to, deep contempt for you!

Initial address: http://blog.csdn.net/fungleo/article/details/53202276

Posted by CBaZ on Sun, 07 Apr 2019 14:48:30 -0700