Preface:

When I took over the project before, all the requested interfaces were put in api.js one function after another. It was easy to do when the project was small, but when the project was large, it was difficult to maintain the thousands of functions in api.js. In addition, there are many cases where interface data is not directly required by the view, and the data must be processed and cached twice, as well as some common logic that can be extracted. Therefore, in the new project, I adopted the feature of class to abstract and separate the request interface function according to the business logic. After a period of use, I found that the expansibility, maintenance and convenience have been significantly improved.

1. Simply understand the similarities and differences between functions and classes

contrast function class
Cache context or state or data x Square root
encapsulation Square root Square root

2. Comparison of the processing methods of data layer between the old and new projects

The old project API. Js:

New project:

  1. The Http class encapsulates Ajax, and the ClassModel inherits Http and calls the this.request method from its parent class

2. Each class corresponds to each business module, and static methods are used to call methods without instantiation

.vue(view layer) calls interface data

 const { code, msg } = await Device.addDevice(this.addForm);
Copy the code

Class encapsulates API benefits

advantages The paper
The introduction of simple from {GetUserList} from “./api/user”
Code decoupling Each class corresponds to each business module, and the code is decoupled
Record context for complex business Pages,toast prompts, skUs for items, and SPU selections can all be wrapped in class

3. Data flow

The vuex code is also very nice for coupling vue page with vuex. For example, a userList page is used:

1. The userList page calls the User class to obtain the data required by the page

2. User changes the value of storage in the VUex

3. The UserList page listens for changes in the value of storage in vuEX and refreshes the table and toast prompt

The last

Class’s ability to cache data, context, and state, combined with vuex, allows views to focus only on UI interaction logic for deconstruction purposes. Writing a business according to this logic is a significant improvement in both maintainability and ease of use.

If this article brings you new ideas and inspirations, please encourage me to leave a comment like ~~