Vue build project actual combat basic knowledge supplement

One, SPA

  Not referring to the spa. is single page web applicationan abbreviation for . Chinese translation is single- page application or single- page web application , please search for more explanations.

  All front-end people should understand the urlcomposition of :http://www.fengcms.com/index.html?name=fungleo&old=32#mylove/is/world/peace

  The above urlconsists of the following parts: protocol, domain name, file name, get parameter, anchor

  1. http://Specifies the protocol adopted by the page.

  2. It www.fengcms.comis the domain name to which the page belongs.

  3. index.htmlThe name of the file to be read.

  4. Parameters sent to the ?name=fungleo&old=32page by GETmeans of

  5, #mylove/is/world/peacefor the anchor area of ​​the page

  When the first four changes, it will trigger the browser's jump or refresh behavior, and the anchor point urlin will not have this behavior. Therefore, almost all spaapplications use this feature of the anchor point. to implement routing conversion . Taking our vueproject as an example, its local urlstructure is generally in the following format:http://localhost:8080/#/setting/task,可以明显的看到我们所谓的路由地址是在 # 号后面的,也就是利用了锚点的特性。(个人理解)

2. RESTful style interface

  The actual situation is that when we agree on interfaces at the front and back ends, we can agree on various styles of interfaces. However, RESTfulinterfaces are currently more popular, and are more convenient and common in use. Although it has some defects, it is githubalso mainly promoting GraphQLthis new interface style, but the RESTfulinterface relatively common in China. And after mastering the RESTfulinterface style, you will have a deep understanding of the advantages and disadvantages of this interface. At that time, you will naturally think of solutions and implement new and better concepts in the project. Anyone who understands program development should know that most of the operations we do are four-grid operations on the database "add, delete, modify and check". The corresponding interface operations are:

  postinsert new data

  deletedelete data

  putchange the data

  getQuery data

  Note: This is our agreement, not these actions can only do this thing. From the surface, getexcept for other methods, there is no difference, they are all the same. At a deep level, all methods, getincluding , are exactly the same, without any difference. However, we agreed that each action corresponds to a different operation, so that we can standardize all our operations uniformly.

  Assuming that our interface is /api/v1/lovesuch an interface, the RESTfulcorresponding operations using the interface style are as follows:

  1、getOperation /api/v1/love:Get /api/v1/lovethe paging list data, the obtained body will be an array, we can use the data to traverse the loop list

  2、postOperation /api/v1/love:We will /api/v1/loveinsert a new piece of data into , and the data we insert will be JOSNtransmitted using objects.

  3、getOperation /api/v1/love/1:We obtain a data whose ID is 1. The data is generally an object, which contains the information of each field of 1.

  4、putOperation /api/v1/love/1:We submit a new message to the interface to modify the message with ID 1

  5、delete 操作 /api/v1/love/1:我们向接口请求,删除 ID 为 1 的这一条数据

  由上述例子可知,我们实现了5种操作,但只用了两个接口地址, /api/v1/love/api/v1/love/1 。所以,采用这种接口风格,可以大幅的简化我们的接口设计。

三、配置 static 目录

  这个目录比较简单,一般搞成下面这个样子:

├── css             // 放一些第三方的样式文件
├── font            // 放字体图标文件
├── image           // 放图片文件,如果是复杂项目,可以在这里面再分门别类
└── js              // 放一些第三方的JS文件,如 jquery

  你可能很奇怪,我们不是把样式和 JS 都写到里面去么,为什么还要在这边放呢?

  因为,如果是放在 src 目录里面,则每次打包的时候,都需要打包的。这会增加我们打包项目的时间长度。而且,一些第三方的文件,我们一般是不会去修改的,也没必要 npm 安装,直接引用就好了。你可以根据自己的情况,对这些可以不进行打包而直接引用的文件提炼出来,放在资源目录里面直接调用,这样会大大的提高我们的项目的打包效率。

四、封装 axios 工具,编辑 src/api/index.js 文件

  首先,我们要使用 axios 工具,就必须先安装 axios 工具。执行下面的命令进行安装

npm install axios -D

  从之前整理的系统结构里,我们新建了一个 src/api/index.js 这个空文本文件,这里,我们给它填写上内容。

// 配置API接口地址
var root = 'https://cnodejs.org/api/v1'
// 引用axios
var axios = require('axios')
// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/*
  接口处理函数
  这个函数每个项目都是不一样的,我现在调整的是适用于
  https://cnodejs.org/api/v1 的接口,如果是其他接口
  需要根据接口的参数进行调整。参考说明文档地址:
  https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
  主要是,不同的接口的成功标识和失败提示是不一致的。
  另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert
*/

function apiAxios (method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    baseURL: root,
    withCredentials: false
  })
  .then(function (res) {
    if (res.data.success === true) {
      if (success) {
        success(res.data)
      }
    } else {
      if (failure) {
        failure(res.data)
      } else {
        window.alert('error: ' + JSON.stringify(res.data))
      }
    }
  })
  .catch(function (err) {
    let res = err.response
    if (err) {
      window.alert('api error, HTTP CODE: ' + res.status)
    }
  })
}

// 返回在vue模板中的调用接口
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  }
}

  但就是这样,我们还不能再 vue 模板文件中使用这个工具,还需要调整一下 main.js 文件,我们插入标红的代码:

import Vue from 'vue'
import App from './App'
import router from './router'

// 引用API文件
import api from './api/index.js'
// 将API方法绑定到全局
Vue.prototype.$api = api

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

  这样,我们就可以在项目中使用我们封装的 api 接口调用文件了。

export default {
  created () {
    this.$api.get('topics', null, r => {
      console.log(r)
    })
  }
}

  注意:webpack代理之后,接口不需要定死,需要改成:('/api/v1'代理里面的路径)

// 配置API接口地址
var root = '/api/v1'

  此外,还要注意一点,就是this重定向的问题

var v = this
v.$api.get('topics', null, function (r) {
  v.list = r.data
})

五、公用工具函数

  我们可以独立出来写一个方法,然后在所有的地方都可以使用,这样就比较方便了。我们建立了一个 src/utils/index.js 的空文本文件,我们编写src/utils/index.js 文件

export default {
  goodTime (str) {
    let now = new Date().getTime()
    let oldTime = new Date(str).getTime()
    let difference = now - oldTime
    let result = ''
    let minute = 1000 * 60
    let hour = minute * 60
    let day = hour * 24
    let month = day * 30
    let year = month * 12
    let _year = difference / year
    let _month = difference / month
    let _week = difference / (7 * day)
    let _day = difference / day
    let _hour = difference / hour
    let _min = difference / minute

    if (_year >= 1) {
      result = '发表于 ' + ~~(_year) + ' 年前'
    } else if (_month >= 1) {
      result = '发表于 ' + ~~(_month) + ' 个月前'
    } else if (_week >= 1) {
      result = '发表于 ' + ~~(_week) + ' 周前'
    } else if (_day >= 1) {
      result = '发表于 ' + ~~(_day) + ' 天前'
    } else if (_hour >= 1) {
      result = '发表于 ' + ~~(_hour) + ' 个小时前'
    } else if (_min >= 1) {
      result = '发表于 ' + ~~(_min) + ' 分钟前'
    } else {
      result = '刚刚'
    }
    return result
  }
}

  写好代码之后,我们保存文件。但是此时,我们还不能使用我们的这个方法函数。我们必须在 main.js 中将我们的方法函数给绑定上。如下代码:

// 引用工具文件
import utils from './utils/index.js'
// 将工具方法绑定到全局
Vue.prototype.$utils = utils

  还记得我们先前是如何将我们的接口请求函数给绑定上的吗?这里其实是采用了同样的方法。这样,我们写的这个函数,就可以随便被我们调用了。我们再来修改一下我们的 index.vue 中的代码,将 time 调整为:<time v-text="$utils.goodTime(i.create_at)"></time>

  我们在 script 区域,引用一个函数是使用 this.getData 或者 this.list 这样的代码引用的。但是在 template 中,我们是不加 this 的。

六、去掉 map 文件

  当我们npm run build的时候,会生成了一些 .map 的文件,当我们的项目变得比较大的时候,这些文件第一个是非常大,第二个编译时间非常长。所以,我们要把这个文件给去掉。

  我们编辑 /config/index.js 文件,找到其中的

productionSourceMap: true,
//修改为:
productionSourceMap: false,

  重新运行打包命令,没用的 map 文件已经没有了。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324635500&siteId=291194637