Vue 2.0 G trading reconstruction project experience sharing

Background of the project:

G trading H5 is running in multi-terminal gaming trading platform. Based on the level of features and product upgrades to improve the efficiency of the development needs of the project some time ago I had a gradual reconstruction with Vue and Webpack. The so-called progressive, that is only part of each cycle page transformation, does not affect the conduct of other services. This time I modified my buy / order lists and order details I sell.

The share mainly in the following points:

  1. Core Technology
  2. Implementation of Component
  3. Data Management
  4. Code level point improvement
  5. Encountered pit
  6. Continued optimization points

Core Technology

The core technology used in the reconstruction is vue2.0 and webpack1.0. Next to them briefly.

Vue.js frame is a gradual build user interface. Other heavyweight frame is different, Vue incremental development bottom-up design. Vue core library focus only on the view layer, and is very easy to learn. Specifically from the official website to learn its usage.

Webpack today is the most popular front-end resource management and modular packaging tools, it can be a lot of loose modules packaged in accordance with the rules and rely on front-end resources to meet the production environment deployment, it can also be loaded on demand module code division, until the actual when needed and then loaded asynchronously.

FIG introduction to the official Webpack by this picture seen interdependent module file, will be packaged into one or more js file, you can reduce the number of HTTP requests.

Webpack specific usage can refer to the official website .

The reconstructed version of Vue used is 2.1.0, Webpack is 1.13.2.

Directory Structure:

  gmmh5
  |-- build //构建目录
  |    |-- build.js   
  |    |-- dev-client.js      
  |    |-- dev-server.js  
  |    |-- HashedModuleIdsPlugin.js 
  |    |-- utils.js  
  |    |-- webpack.base.conf.js  
  |    |-- webpack.dev.conf.js  
  |    |-- webpack.prod.conf.js  
  |-- config //配置文件
  |-- dist //打包后的文件
  |-- src //源码目录
  |    |--assets           // 静态资源
  |    |--biz           // 页面配置文件
  |    |--common           // 公共方法
  |    |--components           // 基础组件
  |    |--constants             
  |    |--modules           // 业务组件
  |    |--pages           // 页面
  |    |--utils           // 工具函数

How componentization?

Components of benefits not list them, single responsibility, easy to maintain, scalable ...

First of all I have said these two pages are divided by function and presentation components.

Order lists the following page, the page from top to bottom according to the function can be divided into three components: the selected item type, the switching state of the transaction, a list of data and render component

Select the type of goods select-type components are responsible for changing the goodsType, transaction status change-state switching components are responsible for changing the state, the two components will change the parameter passed to import documents app.vue, is responsible for import documents to obtain a list of data, then the data transfer to list the components responsible for the list to show data. The flow of data as shown below:

Order details is the same approach.

Data on communication, between the parent component of the component sub-assemblies sent to the next prop by the subassembly through vue of $ on, $ emit event interface to communicate with the parent component. Brothers components or assemblies deeper level, in the current case does not use vuex using EventBus to communicate. Specific operation is as follows:

First named a event-bus.js, create a new global Vue instance, named EventBus and export the object.

import Vue from 'vue'
var EventBus = new Vue()
export default EventBus

Vue simultaneously introduced in the assembly A and EventBus. When the method in this component "emitMethod" is invoked, it triggers the event "EVENT_NAME", and passed the "payload" parameter.

import Vue from 'vue';
import EventBus from 'event-bus'
Vue.component('component-a', {
  ...
  methods: {
    emitMethod () {
       EventBus.$emit('EVENT_NAME', payLoad);
    }
  }
});

In another component B, we can register an event listener to listen for events delivered by EventBus to the "EVENT_NAME".

import Vue from 'vue';
import EventBus from './event-bus';
Vue.component(‘component-b’, {
  ...
  mounted () {
    EventBus.$on('EVENT_NAME', function (payLoad) {
      ...
    });
  }
});

B components so you can listen for events A trigger assembly, without the need to consider the problem of excessive levels.

Data Management

Part of the complex process order details page shows that it depends on the type of goods and the value of the transaction status.

G has the following page H5 sale item type, wherein the account is also divided into hand travel end of travel, the outer consignment account. Coupons also includes match points, coupons, coupon type common point. The actual type of goods at the processing complex than FIG.

There are different state values ​​for each product type, wherein a maximum value of the account status. Commodity type and status values ​​together determine the content of the page is displayed: Status Description title, top, text, icons, and trading operation item button.

In order to process such data, and not mixed together with the logical page, I make it into the configuration table. Part of the code as follows:

const account = {
  '1': {
    'title': '待付款',
    'topImg': imgState.wait,
    'topMsg': topMsgSource.fromFixTxtByFunc,
    'btns': [btn.cancel, btn.pay]
  },
  '2': {
    'title': '付款成功',
    'topImg': imgState.trade,
    'topMsg': topMsgSource.fromFixTxtByFunc,
    'btns': [btn.refund, btn.selectCheckType]
  },
  ...
}

account type of goods on behalf of the account type. '1', '2' is the state value.

Call the store listing page when the value of the interface to obtain data detail, detail out of goods_type and state_to_out, namely the type of goods and commodities trading status value. Then acquires the corresponding data in the configuration file config file. For example, take the heading Description of the state of title:

const vm = this
let goods_type = vm.detail.goods_type
let state_to_out = vm.detail.state_to_out
title = vm.config[goods_type][state_to_out]["title"]

The advantage is clear, to make any changes in the configuration table can change.

Code level point improvement

Reduce duplication of code

The original code, where there is: a copy of code in multiple places, often do not know where changed where leaked when changes. I will sort out a lot of duplicate code again, repeating abstract package code logic.

After such operation buttons of many functions, it will call the ajax refresh the page, so I pull it out to write a single function:

operateRefresh(url, params) {
      //通用方法 -- ajax后刷新页面
      const vm = this
      utils.get(url, params, (res) => {
        let data = res.data
        if (res.return_code === 0) {
          vm.refresh()
        } else {
          utils.toast(res.return_message)
        }
      })
}
The method of preparation of single responsibility principle

Single Responsibility is an object (method) only one thing. If a method to assume too much responsibility, a responsibility that changes may affect the realization of other duties, modify the code becomes more dangerous.

The transformation I will some big function by function subdivided into smaller functional function. For example, a list of pages to be done at the time of the initial things include: determining pay or sell orders, get the type of goods initialization, data retrieval interface to obtain a list of event listeners and other components:

created() {
    const vm = this
    // 判断用户是买家还是卖家
    vm.judgeRole()
    // 从url获取goods_type以及trade_mode
    vm.getUrlParams()
    // 获取列表数据
    vm.getList()
    // 监听事件
    vm.subscribeToEvent()
  }

Encountered pit

Pit reconstruction process encountered more due to the insufficient understanding of the business, this time with Vue2.0 to reconstruct the pit also encountered some of the Vue.

Since the Vue will perform on the property getter / setter conversion process, so the property must be present on the data object when initializing instance Vue conversion to make it to detect its changes. Vue is adding attribute can not be detected or removed. I'm in the business section of the data attributes to add, and modify, but did not lead to re-render the Vue, stuck for some time at this point. Later I read the official document, found that it can be used Vue.set (object, key, value) method will respond to attribute to a nested object, thereby triggering the updated components:

Vue.set(vm.someObject, 'b', 2)

In addition, because the Vue asynchronous execution DOM updates. As long as the data changes were observed, Vue will open a queue and buffer all data changes that occur in the same event loop. If multiple triggers the same watcher, only once pushed into the queue. If you want to update the DOM immediately after the data changes, you can use immediately Vue.nextTick (callback) after the data changes.

Vue.nextTick(function () {
	// 数据变化
})

Continued optimization points

Business done, I have compiled some can continue to optimize the point:

  1. performance. You can gain the narrow part of the file size can be more efficient use of the cache, the first screen to enhance rendering speed.
  2. Experience. Enhance the experience, and when prompted to add the page to refresh the drop-down interactivity.
  3. data flow. When the integration of additional business in, the structural design of the data stream to be more clear.
  4. Componentization. Base component can be more abstract, beneficial reuse.

to sum up

After this reconstruction, I have a deeper understanding and knowledge of the business, and recognize that in the face of complex business, stop and think about the business scene clearly much more important than hands-on writing code.

The Vue also for a deeper understanding and knowledge, but also to remind yourself daily development need to continuously improve the ability to encode and code quality. In the future, more integrated into the new business of reconstruction projects, but also need to constantly optimize and learning in other areas.

Guess you like

Origin www.cnblogs.com/qianduanwriter/p/11797226.html