[Original] The complete strategy of the front-end separation frame based on Vuejs

Source: Internet
Author: User
Tags script tag

First of all, please forgive the title of this article is a bit big, but not for grandstanding. This article takes this title mainly has 3 reasons, this is also the original intention of writing this article:

(1) At present, almost no search in the country to fully explain how to build a front-end separation framework of the article, talk about the separation framework of the front and rear end of the idea of less, and I hope in this article can be fully and in detail the team in the front and back of the separation of the exploration of the building ideas, best practices and architectural ideas

(2) The front-end separation framework built by our team is not simply assembling the knowledge fragments on the Internet, but starting from the global, according to the entire system to the top of the front and rear separation framework of the design, so far, we can say that our framework has fully realized the separation of our front and rear end of all expectations;

(3) We have created some innovations in the construction process (e.g. the largest innovation is the building of API document servers), and hope that these innovations will provide some useful ideas for your team in the exploration of the front-end separation.

This article is suitable for the reader object: The software system architecture has certain experience + to the Web front-end/client software development has a certain experience + server-side development has some experience.

Note: the "front end" mentioned in this article mainly refers to the Web front end, of course, in many cases also applicable to the client software, such as desktop programs, apps and so on.

Chapter One why the front-end separation

1, quote "Why I do not like the" front and back end separation "(personal view, Welcome to spray)"

First of all, you can read the Chinese version of the original text: Https://www.v2ex.com/t/298014?p=4, a very interesting article, the author of writing humor, reading is very easy.

There are several views in this paper that I particularly agree with, such as:

(1) The front and back end does not separate the team, the Frontend engineer is the page Aberdeen discourse right is very weak, the technical Daniel are in the back end, the front end is equivalent to the back-end engineer to do the job; front-end engineers have little promotion opportunities, low salary, development prospects are slim;

(2) After the separation of the front and rear end, better recruitment, team coupling less, more clear responsibilities.

But there are some points in the text that I do not agree with. For example, the author finally recommended "All-stack engineer", although the author years ago is a full-stack engineer, but I know that the advantages of the separation of the front and back is far greater than the benefits of full stack engineers. There are 4 reasons for this, see the next section.

2, why our team to use the front-end separation

Our team ultimately decided on the 4 main reasons for the front-end separation Transformation:

(1) All-stack engineers are difficult to recruit, difficult to cultivate, many back-end developers are reluctant to learn the front-end technology, and many front-end developers are afraid to learn back-end technology;

(2) If the front and rear end is not separated, the work of the Frontend engineer must rely on the back-end engineer, the front-end engineer turned into a handyman, career prospects bleak;

(3) The front-end and back-end engineers are independently developed and greatly improve the development efficiency after the front and rear separation.

(4) In a comprehensive way, the cost of separating the front and rear ends is much lower than the cost of all-stack engineers; At the same time, the efficiency of front-end separation is far greater than that of coupling work;

However, our team has only recently started to fully implement the separation of front and back, because I know that the above 4 reasons for the beautiful vision, the actual effect will be greatly dependent on a key link:API Document server . An on-the-Go API documentation server will make the front-end development work painful, team contradictions increasingly sharp, will eventually reduce the quality of the program, and then no one willing to maintain.

In March 2018, I finally completed a near-perfect API Document server construction scheme, which fully implemented my API document server to expect all the features, and then spent a weekend development completed.

In the next chapter, I will elaborate on the importance of the API documentation server and share our team's own build solutions.

Chapter two the most difficult and crucial link between front and back end--api Document server 1, what is the API document server?

Please look first.

As shown, the front-end developers can independently develop, run independently, and debug independently, and the interface between them is defined by the API document server. Usually, the loading of a page or the submission of a form, there is data between the client and the server side transfer, and the API document server is specifically used to generate API documentation. With API documentation, front-end developers can generate simulation data (mocks) based on API documentation, and then use mock data to complete page styles and page interactions, and with API documentation, backend developers can complete request processing and return response data based on API documentation.

The API document server (typically a Web server) is a server that dynamically generates the latest version of the API documentation and supports local maintenance + remote access.

(If your project is still using static API documentation, such as Word documents, you must experience great pain.)

2, why the API document server is the most difficult, the most critical link?

Why does this article specifically write a section to describe the importance of API document servers? Because the author believes that many teams in the exploration of the front and back end of the difficult, perhaps the most important reason is that the API document building scheme is not enough attention (because the ready-made scheme abound, such as Word Document API carrier). Therefore, I hope you see clearly the front and back end of the process of separation of the most important one, not the prototype, not the design, not the development, nor the test, but the preparation of the API documentation/maintenance/publishing/reading.

Then let's recall a few key steps in the software development process:

(1) The Product manager needs to draw the prototype;

(2) UI designer to design drawings according to the prototype;

(3) Test team to write test cases according to the product prototype, develop test plan;

(4) The architect writes API documents according to the prototype;

(5) Front-end engineers to complete business development based on API documentation;

(6) test, fix bugs, release.

In this process, the API documentation links directly to the front-end and back-end two development teams, and is the most time-consuming part of the entire software development process. Once the API documentation is not properly written, or the maintenance is too cumbersome, or reading inconvenient, will greatly affect the development efficiency, affect team morale. While other links are usually not cross-departmental coupling, the common solution is very mature, and the resource consumption is far less than the development team, therefore, the API document Link has become the front and back end of the separation team the most critical link.

If you have been involved in the development of the front-end separation team, you are likely to have a deep understanding of the scenario described above.

Next I say why API document server is the most difficult link. This is also to let everyone do the psychological preparation: building the API Document server is not as easy as imagined.

First, the biggest difficulty is that there are already a lot of ready-made API documentation services in the world, such as using Word/excel as the carrier for APIs, or using frameworks like swagger. The first response of most of our architects, including the author, is to look for ready-made alternatives and compare the implementation of each scenario with the difficulty and applicability of each. We (the architects) eventually find a way to find a perfect solution, but have to choose from a variety of out-of-the-box options, and we seldom think about whether it is possible to build one yourself, even if sometimes you want to build one, But often the thought of the difficulties (or even the impossible) and the project schedule pressure may be a scratch.

The author's team also used Word documents and swagger in projects prior to 2018, but I am a perfect person, I have not stopped thinking to build a perfect API Document server solution, until March 2018, finally a spark, Solved a key problem in the building process (API version management), so that the front and back of our team to separate the road.

In fact, the program described in this article for users can also be said to be ready to use, because everyone registers an account can be used. But the purpose of this article is not simply to tell everyone that we have made a new API document server, but rather to share with you why we are doing this document server and why.

3. Why don't we use Word documents as vectors for API documents?

Using a Word document (or Excel) is the most backward way, and its drawbacks are obvious:

(1) With more than one API, maintenance and reading becomes extremely difficult;

(2) Each time the API document is modified, it is necessary for the modified person to maintain the revision record, which is against human nature, and if you want to maintain the version history based on a single API, that can be regarded as a violation of the heaven;

(3) in Word, it is very difficult to write the data structure in JSON format, if it is used, it will greatly increase the maintenance cost.

Speaking of the shortcomings of the Word document, follow the routines should say the advantages of the Word document. Well, the advantage of a Word document is that it's easy to spread and read offline, but unless your project's API documentation is maintained on an annual basis, it's too early to give up word.

4. Why don't we use swagger (and similar programs)?

Considering that the reader of this article may have never contacted Swagger, the author first has to say that swagger is what to do, as well as its advanced (no certain advanced how will get so many people's pursuit is it).

Swagger is an API document generation framework, which, frankly, is a class library that, after integration into the system, is able to read the API documents defined by the backend code through reflection, Java and. NET system has a corresponding version.

Swagger's greatest advance: no special people to write API documentation, automatic code generation API documentation, API document maintenance cost is very low. Swagger there are some other small advantages this article does not elaborate, because those are not the main reason why we choose swagger.

So what's the swagger that's not perfect enough for our team to end up completely swagger?

Swagger is not the perfect place:

(1) The API document generated through the swagger can not see the version modification record, you do not know when the backend developers quietly changed the next API document and forgot/intentionally do not notify the front-end developers, such a pot front-end back too much;

(2) The interface documentation is written by the backend developers, the front-end developers are actually lower in status than the backend, and the front-end developers will still often find backend developers to communicate and modify the API documentation (strong dependency still exists);

(3) Originally Swagger API definition should be written by the architect or project manager, but because the backend developers can directly change the document, which results in the actual effect is: Basically the API documentation is directly written by the developer (or modified), its quality level is difficult to achieve expectations;

(4) Swagger the class that generates the API document may be defined as a multi-tier reference association, but this class is too easy to be modified by the developer, or accidentally changed to, if the developer forgot to notify the front end or only to notify the partial changes, it will cause serious problems;

(5) The use of swagger syntax to write API documentation, in fact, is still very troublesome, we hope this syntax can be super simple;

(6) Swagger will contaminate your code.

On the above point (1), I would like to share with you some interesting work. When our team used swagger, sometimes our Java developers found that the naming of a field was wrong, but he thought that the client developer had not yet done this, and quietly renamed the name. Later the test submitted the bug ....

This article lists these shortcomings of the swagger, in fact, each one is not big, this is the reason so many teams can endure it all the time. Swagger these shortcomings in fact, the main problem is that it makes the API writing/modification is too easy, so that the software development process and management process is too error-prone. If your team has established a strict management mechanism, it can still use the swagger very harmonious, but this is not the author, as an architect, can put aside the reason for responsibility.

As an architect, I think a good framework should make it less prone for developers to make mistakes, and even eliminate the developers from writing the wrong code. On this point, the author will take our example of the transformation of hibernate into a more detailed explanation: How to make it more difficult for developers to write wrong code is an important criterion for evaluating an architect's ability.

At this point, the author has brutally criticized a lot of the team's API document scheme, if you feel unwell, I can only apologize.

In the other solutions to the shortcomings, in fact, I have gradually revealed that our own API Document service framework will be solved problems. So, let's look at our solution, and why we're designing it.

Chapter three of our own API document service framework in detail 1, my mind of the API document server should be what it looks like?

I have a habit of thinking when writing code or architecture, that is, no matter how complex a specific solution is, I will first think about the best way to deal with the problem, and then think about the best ways to do it, which can not be achieved and only use the next point of the scheme, Then the next point of the scheme is acceptable.

For the API documentation Service Framework, I have already had expectations in my mind:

(1) The syntax of writing API documents must be very simple, but also very flexible, for most common APIs have to be able to write quickly, for some special APIs, but also to support custom writing;

(2) Each API document can be very easy to define the request and response data structure, it is best to automatically generate the request and response samples, more importantly, the generated sample must appear to meet the business needs of real data;

(3) can be very convenient to write data in JSON format;

(4) API documentation is very simple to publish, preferably in a few seconds to complete;

(5) The source file of the API documentation is best independent of the project source code, can not pollute the project source;

(6) Each time you modify the API documentation, it is best to automatically create version history, and to be able to easily view the historical version;

(7) can be accessed through a Web browser;

(8) When the number of APIs reaches tens of thousands of times, can present a tree-shaped directory structure, easy to read and search;

Well, about these 8 features, let's see how we do it.

2, our self-created API document service Framework core work principle

First, look at the simple framework:

This framework is not complicated to build, it can even be said to be simple. The techniques and tools used are as follows:

(1) Use JavaScript as the programming language of the API document source files;

(2) using any JavaScript-enabled IDE as an API document authoring tool, our team uses IntelliJ idea;

(3) Use SVN server as version management tool to manage API version;

(4) The Web server can be used to build whatever frame.

Core Working principle (4 steps):

1 , get JS directory Structure . When the user enters the API document service address in the browser (for example, http:// api.some-domain.com), the Web server obtains the JS file (i.e. the API definition source file) directory from the SVN server according to the pre-configured SVN address and account information, then the Web server responds the tree directory of these JS files to the browser (not the JS file content, just the JS directory structure), after When the user clicks on a JS file name, the corresponding JS file content will be loaded, so that even when the API document is increased to tens of thousands, it will not affect the loading speed too much.

2 , loading Apihelper.js file . After the previous response is complete, the page loads a particularly important apihelper.js file through the script tag. What does this JS file do? It will greatly simplify the syntax of our API documentation! First, the file defines a Apihelper object under window that encapsulates a large number of static methods that are primarily used to define API document data structures. For example, the ApiHelper.response.page (object) method will respond directly to the data structure based on the object's component page.

3 , load a single API. When the user clicks on an API, the page dynamically loads the JS file into the browser and executes it. So what code does this JS API file actually execute? In fact, it is very simple, each of our JS API files in the window below the definition of an API object (of course, according to a certain data structure defined by the object), when the JS file execution is completed, The Window.api object under the current page has been updated, so we only need to adjust a render () method to render this Window.api object in HTML. In rendering the Window.api object, we make full use of the dynamic of JS language and its reflection mechanism, which greatly simplifies the definition of API document.

4 , view a single API version of History . After loading the JS file of a single API, we can find the modified record of the JS file through SVN, and then render a revision record list, click on each revision to load the once version of JS, Now that the Window.api object has been replaced with a historical version, we just need to call the previous Render method again to render the Window.api object again, so that we can do a quick version switch and a smart comparison.

The above is the core of our API framework working principle, is not very simple! If you have extensive experience in software architecture, I believe that you have fully understood our thinking and can build a similar API document service framework. But perhaps for most readers, reading here is still a bit foggy. Don't worry, the following is an example of an API document in our project, combining the interface and code to illustrate the core principles.

First, look at the reading interface of one of our APIs (a page with 4 tabs):

The above 4 images are the definition documents for a request, response, request sample, and response example for one of our API documents. This document is obtained by parsing the Window.api object. Although this document defines so much content, the source file for this API is very simple, see:

A few, maybe just over 20 lines of code to complete the definition of such a complex API! This is all thanks to the power of JavaScript's dynamic language!

If you read the API source files above, you may find that we have defined a number of special grammars, such as the underscore "_" attribute representing the overall description of the current object, while the Post property under the API object defines both the HTTP method and the request URL. There is also the APIHELPER.P () method to place the definition of a request/response field in one line of code, with 4 parameters: Data type, nullable (String oh), sample data (not just string-oh), and field descriptions. The final effect of this JS file is to define the Window.api object, and then after the browser has loaded the JS, our render () method can render it.

Next, let's go to the browser console to see what the actual Window.api object looks like:

As you can see, this Window.api object is actually very complex, and the reason why our API source files are so simple is that apihelper.js does a lot of things, which simplifies the writing of the API. This is what an architect should do: give as many things as possible to the framework to complete, and allow developers to write as little code as possible to get the job done, with the assurance of scalability.

Finally, it seems that only the render () method is in the Web page, but the author does not intend to present it in this article because it is really simple and has moved away from the main thrust of this article. If you are unable to write the render () method based on the information above, then you can use our ready-made solution (add JFrame official QQ group to understand it: 651499479).

Ultimately, our API documentation Service Framework fully implements our initial expectations:

(1) The API document writing syntax is super simple, extensibility is strong;

(2) very easy to write real request and response examples;

(3) It is very easy to write data in JSON format;

(4) Publish API document Super simple: Submit svn;

(5) API document source files are completely independent of the project source code;

(6) Modify the API document will automatically create version history, in the Web page can be very easy to view/compare historical version;

(7) Access through a Web browser;

(8) When the number of APIs reaches tens of thousands of times, can present a tree-shaped directory structure, easy to read and search;

This concludes our API documentation service framework. It's a bit long, because I think the API document framework is really the most important part of the front-end separation process, because the API document framework is more uncertain than the backend framework or the front-end framework, and it is difficult to achieve high-quality API document framework based on existing open source projects. Unlike front-end or back-end frameworks, where there are many mature scenarios, it is relatively easy to complete high-quality front-end and back-end frameworks.

Fourth chapter of our front-end separation framework

Our front-to-back separation framework uses the following technologies mainly:

(1) using Vuejs as the front-end template engine;

(2) using jquery and the JS control we accumulated for many years as DOM Operation function library;

(3) The backend uses the Java system of Spring MVC to return HTML.

Next I will explain why we chose these technologies.

1, the author's understanding of Vuejs

First of all, I believe that many people to vuejs or react in the end what is not very clear, because their official website tells a lot of features, so that we can not understand what Vuejs's job is. The author in weigh Vuejs and react process, also feel very confused. Because according to Vuejs's official website, it seems that I should build a project project based on the. Vue file and compile it into HTML, CSS, and JS through the compiler. and the Vuejs official website also introduced a lot of Nodejs-based Vue service-side rendering, Vue Ruoter, Vue Loader, scale, and packaging tools Webpack and so on. It looks like this is a new, complete, front-end development framework that includes a server-side.

I believe the Vue website is really a new, complete front-end development framework. However, in the author's view, this framework is not the best front-end development framework. For a front-end developer who does not understand the server backend architecture, using Nodejs to build a Web server is indeed an optimal choice because Nodejs is more than Java,. NET is too simple, I believe the Vue official website is also for this reason to do a lot of intervention on the server-side solution.

However, our team has a very mature Java server back-end framework that requires just a few lines of code to complete the heap of features that Vue officially describes. I am also the Vue official web site introduced these service-side program read for a long time, only to understand the real intentions of Vue official website, and finally understand that the architecture described in Vue's website has not been based on our Java server to add a few lines of code to get the good architecture.

This is one of the biggest puzzles I've encountered when I read the Vue website. The final decision: we only consider Vue as an HTML template engine, which is what Vue does.

This decision is not easy, because it makes our frame look less trendy. Because of the knowledge that Vue has introduced on the web, other than the knowledge of Vue as a template engine, we have no use for other knowledge.

Vue Online also has an invisible basic understanding is not introduced clearly, because I found that the Vue online almost all the knowledge is based on the SPA (single page application) under the framework of the description, including Webpack, Vue ruoter and so on. But our system is very large and complex, and it is impossible to use the spa architecture at all. On this point, I also read a long time to find that the default setting of the Vue website is the spa architecture.

2. Why do we choose VUEJS?

After the front-end separation, the frontend engineer needs to render the data obtained through the API to the page, although it can also be assigned to the page by jquery, but this is too inefficient, or it can be done by stitching HTML in JavaScript, but it is too difficult to maintain the HTML code, Also difficult to read. So the best way is to use the template engine.

The front-end template engine is similar to the back-end template engine, such as JSP or cshtml (Razor), whose syntax is very similar and they implement almost the same functionality: binding data to HTML templates. Both Vuejs and react can act as such template engines. We finally did not choose react but chose the vuejs reason only one, that is Vuejs is the real response, and react change model after the need to manually call SetState to update the UI, this is completely intolerable.

For this reason, we can only choose Vuejs as the template engine.

3. How our front-end framework Works

Although this article is a bit long, our front-end framework is very simple, which is why we chose not to use the. vue file to build the project because it's too complicated.

Core working principle:

(1 ) define the page URL format . The address format for each of our pages is approximately the same: Http://www.your-domain.com/admin#home/index. The admin represents the module name, #后面的home代表子模块对应controller, and index corresponds to the method inside the controller. So when you switch pages in the same module, only the hash value of the address is changed, and the browser does not jump. However, when the page is switched, the framework can load the current page based on the hash value if the user clicks on the browser's refresh button.

(2 ) According to the URL load layout.html. When the server receives a request for a "/admin#home/index" address, it returns a layout.html, regardless of the value of the subsequent hash. The layout.html file contains the basic framework of the page, such as public JS, CSS pages, navigation, footer, and other common elements.

(3 ) initializes the Layoutvue. After the layout.html is loaded, JS will generate a Vue instance based on the HTML structure of the layout.html, and give all the Dynamic HTML layout.html below to the Vue instance hosting it, such as displaying the corresponding navigation menu according to the user role, and displaying the user in the page header Human information.

(4 ) according to Location.hash by jquery Ajax loading the appropriate content HTML file . At this point we will define another interface on the server side, returning the HTML code for the content page based on its path.

For example: Get/admin/getpage?path=home/index.

The HTML of the content page, in addition to the HTML code, contains the JS and CSS required for that page. This way, when the content page's HTML is rendered to a container div in layout, the content page JS is loaded and executed. So what is the logic of JS on the content page? Of course it is initializing the Vue instance of the content page and taking over the dynamic HTML generation work of the content page.

The above 4 steps can be expressed in simple words:

Read here, if you are very experienced in software architecture, then believe that you have fully understood how our front-end separation framework works, you should be able to follow the idea of this article to complete your own front-end separation framework. But for most readers, it may be possible to read this just to understand what is going on, and if you want to start building it yourself, you may be embarrassed by the impossible. Don't worry, I'll take our framework for example, step by step through the code to show the building process of our framework.

4, step by step to build our front-end framework

(1 ) page address generation . The server is based on the synchronization request URL (/pe#home/index ... ) responds to a layout.html. See Java source code:

Java code in the front-end framework of all the back-end processing code (please read this sentence, a bit around the ha), is it very simple? Although simple, the function is very powerful. As you can see from the code above:

A. As long as the URL begins with "/pe#", the server will return directly to the layout.html page in a directory;

B. Front-end developers can easily create directories, subdirectories, and HTML files under "/modules/pe/views/", and then request similar "/pe/page?path=home/index" via Ajax Such URLs directly load the following HTML file, so that front-end developers do not need to move a line of back-end code, just by convention to build directories and HTML files can be loaded in the browser. This way, front-end developers do not have to rely on back-end developers to get page addresses, and front-end developers can create page addresses themselves!

In the Java code above, you can also merge the synchronization request with the asynchronous request into one (@GetMapping ("/pe/*")), and then inside the method determine whether it is a synchronous request, and if it is a synchronous request, return layout.html, otherwise return to the content page. This is not a monitoring hash change, but each URL address looks like a synchronous request address, such as "/pe/home/index" url into the server, the server first returns layout.html, and then layout.html to initiate an AJAX request "/ Pe/home/index "The server returns the content page HTML. In our project, we prefer to use the method of monitoring hash changes. Of course, I think both of these methods are OK, if you want to switch later is relatively easy.

(2 ) layout.html. Let's take a look at what the layout.html of the server first returns looks like, see:

This HTML file is the server's synchronous response content, but also the entrance of each of our pages. At this point we need to understand a Web page as an app (app), and this layout.html only defines the app launch portal and frame. You can see that the file refers to the basic CSS and JS, its final core.js internal completion of the app initialization. Let's take a look at the main part of the code inside this core.js.

(3 ) Core.js. The code to complete the app initialization is as follows:

The above example code is the author for the sake of streamlining, in fact, this JS file in the process of completing the initialization of the app also did a lot of operations, such as obtaining user login information, get the page dynamic navigation menu data, and then the obtained data through a Layoutvue instance to the page, Thus the Layoutvue instance completely takes over the entire HTML rendering work in the layout.html.

The last step in app initialization is to #后面的路径加载内容页HTML到一个id为body的DIV中了 based on the URL. How the server responds to the URL asynchronously (/pe/page?path=home/index), refer to the asynchronous request for Java source code (Pepage method) in the first section of this chapter.

(4 ) content page HTML. Look at the HTML of the content page loaded by Ajax:

As you can see from the above code, each content page corresponds to a JS and a CSS file, and then the HTML code begins with a div with the page ID. Of course, these are not necessary, but our project specifications, of course, I also suggest that you can refer to our specifications.

When the content page HTML is loaded, it will execute its referenced JS file. Next, let's take a look at the JS code of the content page.

(5 ) content page JS code . Please see:

This JS file first consists of a self-executing function package, the advantage is to avoid inadvertently define the object under window (coding developers write the wrong code), which is one of our specifications, in fact, all of our project JS files are wrapped by self-executing function.

The main entrance to the above code is the callback function of the Vue.nexttick method. Vue.nexttick is a very important method, but the official online does not give him a particularly obvious position, so I would like to say two more sentences, this method has what use. This has to go back to Vue's render mechanism. When the Vue instance discovers that the bound data has changed, Vue takes the form of updating the UI element asynchronously, so that when we modify the data, the DOM element is not generated, and if the DOM is then manipulated (e.g. through jquery), then the DOM element is not found. So be sure to use Vue.nexttick to manipulate the DOM elements that affect the Vue data after changing it.

Then go back to the top code. In the Vue.nexttick callback, the first is to initialize the Vue instance of the content page to take over the rendering of the div with the page ID and all the DOM elements beneath it.

At this point, a complete page, even if the load is complete, the user in the browser can see the full page.

This is the entire workflow of our back-and-forth separation framework, and I hope the author has explained the process clearly enough, and then you can start building your own front-end separation framework. But before you actually start, I would like to share with you a best practice for our back-and-forth separation: mock, see the next chapter.

Fifth chapter the API mock thinking in the front and back end separation frame

To achieve true front-to-back separation, it is necessary to use the API mock (analog data). There are two benefits to using mock data:

(1) Front-end developers can generate mock data based on API documentation, and can complete the development of the entire business process before the backend developer publishes the API;

(2) Use mock data to debug page styles and debug page functions at a lower cost and faster, by modifying the way the mock data is directly modified.

In this article, I'm not going to recommend any mock frames, because we don't have to: we're going to create more realistic mock data in a way that's purely handmade data.

We need to use mock data in the back-end separation framework, primarily the API, so other usage scenarios (such as hardware mocks, third-party system APIs) are not described in this article because their mock thinking is actually the same.

1. Global Mock switch

The mock data of the API is divided into two categories: a fragmented, hand-initiated Ajax API request, and an AJAX API request encapsulated inside the control. No matter what kind of mock, we first define a global mock switch in the core.js that is loaded on each page: Mvcapp.mock = True/false, and then, after the page is loaded, determine if the mock==true is set, prompting the user/ The developer is currently using mock data!

Why set such a global mock switch? Mainly based on the following two points:

(1) After setting the global mock switch, it is no longer necessary to set the mock switch for each page, which is easier to maintain, and avoids multiple mock switches in the project and is difficult to unify the switching state;

(2) If you forget to turn off the mock switch at the time of release, a running Publisher will notice that the mock switch has been left out and then can be quickly repaired and then republished to avoid accidentally updating the formal service to a mock data source.

Because of the above two points, our global mock switch can help programmers and publishers to make mistakes more easily.

The following author will show you how the global mock switch works with the page API to complete the mock state control of the entire site.

2. Mock of Common API

In our front-end framework, we used grunt to package all the JS files of the entire page into a JS file, so in our front-end frame, each page corresponds to a JS source file folder, in the packaging, Grunt will merge all the JS files in that folder (the compression confusion will be performed when publishing to the production environment). is displayed in our admin side of a list page corresponding to the JS source file directory (Index folder):

You can see the folder below the first JS file called 01.page.js, this JS is the entire page of the portal, including the definition of the page all the configuration (such as the use of Ajax URL). The 2nd file is a 02.api.js file that contains all of the Ajax requests. We encapsulate all of the Ajax requests in this file and for better mocks.

Let's see what this 02.api.js looks like:

As you can see from the code above, We define the Page.api object two times, and in the middle there is an if judgment, that is to judge whether our global mock switch is in the open, if the mock is turned on, then return will not be executed to continue the second paragraph Page.api object Assignment code, so the first code definition of the Page.api object is overwritten The other JS files on this page will use the mock data. If the global mock switch is turned off, after the first Page.api object assignment code executes, the return statement under if is called, so that the second paragraph of the Page.api object assignment is not executed, and the other JS files on this page will use the real data.

This is the application of the global mock switch in the page, which is simple and flexible to use. In this way, front-end developers can complete styles and interactions through mock APIs before the API is developed.

3. Control-level mock with grid control as an example

In the Web front-end development process, you will definitely use a large number of controls (UI components). If the control, such as a grid, encapsulates an AJAX request, its Ajax mock-up is difficult to do with the mock method in the previous section.

Below, the author will take our project grid control as an example, to give you detailed elaboration of our transformation process.

Because the grid controls in our project were developed by ourselves, there were only 300 lines of code, but they were powerful and highly customizable. Therefore, it is easy to transform our grid.

First, we define a Vuegrid class that inherits from the Grid class, and then overrides its loaddata as an Ajax method, see:

After the transformation of the Vuegrid class more than a getmockdatafunction this property, in the LoadData method, first determine whether the grid instance set the Getmockdatafunction property, If you set the Getmockdatafunction method to determine whether the return value is empty, if the return value is NULL, the real data is also used. So the conditions for using mock data are harsh: The Getmockdatafunction property must be set and its return value cannot be null.

Then we also expose a method for setting the Getmockdatafunction property in the Vuegrid class, such as:

In initializing the grid and Vue page JS (01.page.js), we use the following code like this:

When initializing the Vuegrid instance in the above code, the mock data source is set to page.api.mockSearchList this method. We can control whether the Page.api.mockSearchList method is null by using the global mock switch to control if the grid uses mock data.

Take a look at the code in 02.api.js:

In the above code, If Mvcapp.mock is set to False, then page.api.mockSearchList will not be defined, that is undefined (null), if Mvcapp.mock is set to True, then page.api.mockSearchLi St will be assigned a value, and the grid will use the mock data.

Finally, in order to facilitate people to understand the entire grid control the use of the process, I give you to see our own written Vuegrid HTML code, very simple, very flexible, support sorting, paging, support JSON and HTML two data formats:

At this point, the mock transformation of our grid control has been fully completed. After the transformation of the effect: do not need to modify the 01.page.js, do not need to vuegrid.js, do not need to modify 02.api.js, Simply modify the value of the Mvcapp.mock to toggle the use of mock data .

In this way, the state control of our mock switch is very simple, and, most crucially, it is not prone to error!

Sixth Chapter Conclusion

Finally, I will take you back to some of the key technologies, viewpoints and views mentioned in this article:

(1) Front-end separation is the most critical link is the API document service framework, there is no good API document service to support, the front and back end of the road is difficult to separate. The author suggests that you build yourself according to the ideas provided in this article, or consider using our ready-made framework;

(2) Vuejs website Introduction of large-scale architecture is not necessarily the best, if your team has a back-end architect, I suggest that only the Vuejs as an HTML template engine, as for the Vuejs official website described other features can be ignored;

(3) Vuejs asynchronous rendering is a very important point of knowledge, but Vuejs official website does not put it in a conspicuous place, so must master the Vue.nexttick method and its working principle;

(4) Vuejs is completely compatible with other third-party frameworks/libraries, and the key is to master how it works, such as Vuejs in our project, interacting with jquery, jQueryUI, and our own JS Control library. Although the Vuejs official website recommends that DOM operations be taken over by Vuejs, the author still suggests that it is often more advantageous to use jquery to manipulate the DOM, because jquery is more encapsulated (such as our grid control, which is simple to use. That's because internal jquery encapsulates a lot of operations);

(5) True front-end separation must not be separated from the mock, do not think that the mock is a how complex and how advanced things, in the author's opinion, Mock is only a thought, you just understand its core thinking, the mock frame of their own writing is the best use;

(6) Separation of front and back, if done, profit far outweigh the disadvantages. From this time after the separation of our team, its positive impact on the team is obvious; in the long run, the separation of the front and back to promote social division of labor, so that the company's talent training path clearer, more efficient, more competitive.

Finish

[Original] The complete strategy of the front-end separation frame based on Vuejs

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.