This article can actually be seen as a new project to take over the front end? There are a few things you might want to keep an eye out for, mostly lessons I’ve learned from writing code on a regular basis

Use the typescript

A typescript project will be 30% bigger than a non-typescript project. Of course, the extra 30% is only the code you need to write locally. Once the project is packaged, if you use TS, the project will be almost the same size

I don’t want to go over the benefits of TS, but the most useful is type checking and enhanced tooltips in the editor. It’s important to note that while you’re already working with TS, try to maximize the benefits of TS. Don’t write anyScript in typescript to get lazy, otherwise you might as well not add it

On the other hand, often hear people say, small projects don’t need to access ts, only big project need, in fact, as I feel, don’t need big small, easy to cause confusion, you write to the company’s projects where certainly not small, and definitely not finished no matter, follow-up is sure need to maintain multiple iterations, no brain access

As for your own personal projects, it’s up to you, because the code is your own and you should know what you’re writing

Don’t put too much logic in templates

Whether the react or vue, template or JSX don’t write too much logic, the template is used to screen layout and try not to do other things, logic and all the best in js, with a large number of logic of the template, will not only disfigures the template, it is hard to see clear the page layout, maintenance is also very difficult at the same time, Because the template supports only part of the JS syntax, not all of it, a piece of logic may be easily implemented in JS, but in templates, because of the syntax limitations, it takes a big circle to get through

Taken as an example, when a commodity, there will be a corresponding commodity status of schedule page, may have a button at the bottom of the page, when the goods haven’t taken delivery, according to rush shipment, after the goods shipment, confirm the delivery of display, after confirm the delivery of goods, according to evaluation, this is the most basic, complex, may have more than five buttons, It may be difficult to display several buttons at the same time according to the state of the current flow, adding up to a dozen button arrangement display

The most common solution I’ve seen for this is directly in the template if.. Else, if set the if, if the judgment of the body may have to depend on more than one condition, that is horrible, half of the screen template, it is found that is really just to show the most the two button at the bottom of the page, want to change which button, the first clear layers of tracking the button wrote what and which a few conditions, in order to take into account the UI, We also need to confirm whether the change will affect the display effect, which is a waste of time

<div class="bottom_btn">
  <div class="single" v-if="status === '1'">
    <button @click="buttonClick('sendBySelfBtn')" class="button">Modify the logistics order number</button>
  </div>
  <div class="single" v-else-if="status === '2'">
    <button @click="buttonClick('moneyDetail')" class="button grey" >Check the payment progress</button>
  </div>
  <div class="single" v-else-if="status === '3'">
    <button class="button grey" @click="buttonClick('cancelBtn')">Cancel the consignment</button>
  </div>
  <div class="single" v-else-if="status === '4'">
    <button class="button grey" @click="buttonClick('reSell')">Back on</button>
  </div>
  <! -- Display two buttons at once -->
  <div class="double" v-else>
    <button class="button grey" @click="buttonClick('cancelBtn')">To send a</button>
    <button class="button grey" v-if="status === '5'" @click="buttonClick('cancelForOnlyTip')">Cancel the consignment</button>
    <button class="button grey" v-else @click="buttonClick('cancelBtn')">Recalled products</button>
  </div>
</div>
Copy the code

If you follow the template to template and logic to JS specification, then all you need to do is write the layout clearly on the template and put the logic directly into JS, even if you still write if.. Else, js code if… Else is also better than JSX where JS mixes with HTML if.. Else nice point, not to mention, using JS to write, can completely optimize the logic, what map query, what strategy mode use a little use, will look a lot better

<div class="bottom_btn">
  <button class="btn1" @click="btnClick(btnData.leftEventName)">{{btnData.leftTxt}}</button>
  <button v-if="rightBtnTxt" @click="btnClick(btnData.rightEventName)" class="btn2">{{btnData.rightTxt}}</button>
</div>
Copy the code

The above template is a lot clearer, I know at a glance here put one or two buttons, as for the button click event is what, what is the text of the button, when to explicit what button, explicit one or two buttons, that is js things, the template is only responsible for display

updateBtn () {
  const statusSignleBtnMap = {
    1: {
      txt: 'Change the logistics number'.eventName: 'sendBySelfBtn'
    },
    2: {
      txt: 'Check payment progress'.eventName: 'moneyDetail'
    },
    3: {
      txt: 'Cancel consignment'.eventName: 'cancelBtn'
    },
    4: {
      txt: 'Reshelving'.eventName: 'reSell'}},const statusDoubleBtnMap = {
    5: {
      txt: 'Cancel consignment'.eventName: 'cancelForOnlyTip'}}let btnData = statusBtnMap[status]
  if (btnData) {
    this.btnData = {
      leftTxt: btnData.txt,
      leftEventName: btnData.eventName
    }
  } else {
    this.btnData = {
      leftTxt: 'cancelBtn'.leftEventName: 'Self post'.rightTxt: statusDoubleBtnMap[status].txt,
      rightEentName: statusDoubleBtnMap[status].eventName
    }
  }
}
btnClick (eventName) {
  // Click the button according to eventName
}
Copy the code

All the button information that needs to be displayed is on btnData. If you want to add, delete or modify a button, you only need to modify statusSignleBtnMap or statusDoubleBtnMap. No matter how much logic there is, it is nothing more than modifying the object properties

Branch statement optimization

Business code without if… Else, even some function code is placed in if… In the else block, writing branch statements will significantly improve the code’s readability

Don’t write too much logic in the judgment branch

Down one screen at a time can’t see the end of the branch statements parentheses, continue to look down is easy to forget what is the current case, even double up to clear, from the perspective of the code, and should not be in the logic of a block of code to write too much, if you find is the need to write a long logic, then put the logic in the another function

End branches early

If you find that a branch can end prematurely, end it immediately, and at some point this can greatly reduce if… Else number of nesting layers

function fn1(a, b) {
  let c = null
  if (a > b) {
    c = a + b
  } else {
    if (a === 0) {
      c = b + new Date()}else if (a === 1) {
      c = a / b
    } else {
      c = a * b
    }
  }
  return c
}
Copy the code

Can be optimized as:

function fn2(a, b) {
  if (a > b) {
    // End early
    return a + b
  }
  let c = null
  if (a === 0) {
    c = b + new Date()}else if (a === 1) {
    c = a / b
  } else {
    c = a * b
  }
  return c
}
Copy the code

As you can see, Fn1 has one less layer than Fn2. Else nesting, this is just a simple example code, in general business code if… Else can not only have two layers, when the timing is reasonable, the five or six layers of branches nested flat into a layer, that comfortable……

Key pages do component splitting at source

Site of some of the key page, home page, page for details, for example, at the beginning of the building is probably good planning layout, divided into good child components, don’t say what optimization in advance is not necessarily good, because these key page is certainly need long-term existence and continuous iteration, there is no doubt about it, there is no behind you advance optimization results can’t be used for a basic situation

Without good planning, to optimize the test would be a little human nature behind, because people are inert, and everyone is busy, requirements are written not over, who is willing to optimize code, plus the code does not know by how many people changed early, change other people’s code is to eat shit, optimization of other people’s code is to ascend to heaven, who is willing to do? When many a mica makes a mica finally unbearable want to optimize, you may need to pay several times the energy, plus can accept the possibility of getting a bug to the courage, in order to optimize, why bother to zai?

Of course, the division of sub-components is not to say the finer the better, to maintain a balance, how to grasp the balance? According to my experience, the overall component template to add at least more than 100 lines of js method, if less than the number of rows, consider whether division is too thin, don’t be no more than 400 lines, more than to consider whether can split again, this is the practice of most of the time, also is not absolute, or want to weigh according to the actual situation

For example, for details page, generally can be divided into header banner + product title description area, SKU selection area, evaluation area, detail description + picture area, bottom button area, these areas can basically exist independently of each other, or coupling is very low, can be regarded as independent components for maintenance and management

Reduce component coupling

One of the rules of component partitioning is to minimize coupling

Home page, detail page, such a key page, the need for data and methods will never be less, so much data and methods mixed in the same place, it is not easy to maintain, every modification or call a certain data and method, we must first see what data and methods depend on the current data and methods. Only when you make sure that the current change doesn’t affect other data and methods can you actually start making changes, which is a meaningless and time-consuming repetitive task

And predictably, who all dare not easily delete a data or method, although the data and methods may never use not to, because there are too many data and methods, to clarify the relationship between these data time-consuming, might as well throw in there, can’t go wrong if you don’t change, change is likely to make a bug, in the long run, on the page is invalid code are more and more, Data and methods are also more and more, the logic is more and more complex, in the end, you want to overturn it all over again, but unfortunately, you may still dare not, because you can not even delete a data or method, how can you dare to reconstruct?

If the components are divided well at the beginning and the data and methods are broken into separate components, then there will be less data and methods in each sub-component. Before adding, deleting, modifying and checking, you only need to glance at the relationship between all the data and methods, and the update will be more convenient

Of course, the division of components is not the finer the better, there is a trade-off

If you find A lot of data and methods of the components are A and B component, to modify A component’s big probability can lead to B component updates, so consider component A and component B, merged into one component, one of the main goal is to improve the component reusability, coupled two serious components clearly is not easy to reuse, also some more interactive logic

Component of most of the data and methods should be in internal maintenance, so, after the iteration, which area need to update the content of the to go to the corresponding component changes, will not affect the other components of logic, a small group of public data and methods should be placed on the parent component maintenance, child components directly through the props from the parent in the component data

If you don’t really need vuex, it’s not recommended to use vuex. It’s cool to use, but it’s definitely not as intuitive as props to track. Vuex is also recommended to use vuex only when you feel you need to use it. Most projects don’t need it

The use of good mixin

What do you do when you need to add an operation activity on some key pages, such as home page and details page, which has a short lifetime and may be used only once and never be used again? Direct open masturbation, the data add data add method add method, generally do so

But the question is what do you do after the event?

The best way is to remove all activities directly related to logic and to restore to the page as originally, but usually it is difficult to restore, because you had already operating activities related to logic and the body of the page was logic code mixed together, like put a handful of sand in a heap of excrement in the mountains, can really to pick out all the sand, but it is clear that the time-consuming, What’s more, most people don’t remove broken code at all, but simply put a logical switch in the code that can be turned off and the code stops running or even runs without having any effect on the main logic

As a result, more and more switches were added and more and more failed code was added over the course of several iterations of the operation

More and more sand mixed in the mountain of shit, not only taste and hurt teeth, How Dare You!

My approach is that if the activities related to logic and subject code coupling is low, then consider independent into a component, but in most cases, the operations of logic is closely related to the subject code, coupling is very high, this time it is best to try to all independent activity logic a mixin, decrease as far as possible to modify a master file data, It is best to have as few interfaces as possible between the mixin and the main file, so that if a method in the mixin fails or the mixin is removed, the main file will not be materially affected

The more operational activities are added to the page, the better this division is. The main file only cares about the main logic, and each activity logic has its own mixin file, each of which has its own function, and the complexity of the page will go from exponential to constant as more and more operational activities are added

Another tip is that if you need to modify the mixin’s data or call the mixin’s methods in the main file, it is recommended that the data or method have a clear mixin attribution. For example, the data in this mixin can be named mixinSomeData or the method named mixinSomeMethod. If there is more than one mixin, each mixin can be identified separately, such as mixinASomeData and mixinBSomeData. This way, when you use the data or method in the main file, you know at a glance that it’s a mixin and which mixin’s data or method

Once you’ve done that, it’s easy to remove the mixin file from the master file and delete all references to the data and methods in the mixin

One more thing I want to say about mixins is that if you use mixins, you need to minimize the interaction between mixins and the body code. Otherwise, they are too coupled. To understand a piece of logic, you need to compare it back and forth between two files. The data interaction between these two mixins and the main logic is called a myriad of threads, and a normal logic must be shuttled through the three files, which made me cry

Use pure functions whenever possible

Pure function is to ensure that the same input can get the same output. When calling this function, there is no need to consider whether the variable of higher scope will have any influence on the function operation. The main purpose is also for decoupling

Of course, in many cases, unless it’s a generic utility method, method calls are more or less related to global data, so what we can do in this case is to reduce the involvement of irrelevant high-scoped variables

Make full use of variables

After defining a variable, it is necessary to give full play to the role of this variable. Why should we define variables that are not essential?

Never use two problems that can be solved with one data or one method

I often see in projects that it takes several variables or methods to solve a problem that can be solved with one variable or method, which not only increases the amount of code, but also takes a lot of effort to maintain

For example, if the current order flow status is STATUS: If the status is obtained from the interface, the display logic of the popover component can be done with V-if =”status == 4″. There’s no need to reapply a variable called this.modalShow to control the popover display (if it has any other function), because when someone else takes over maintenance, he or she has to go to modalShow to figure out when the popover is going to show. Find status from modalShow and add another link

Give variables specific capabilities

For projects with separated front and back ends, the main data on the page basically comes from a main interface, and the page data is displayed and rendered according to the data returned by the interface, such as the data format returned by the back-end interface:

{
  "code": "0"."data": {
    "title": "IPhone XS Max 95XIN"."price": "6200"."userName": "Wang"."status": 4}}Copy the code

A common practice is to apply for as many variables locally as the data returned by the interface:

this.title = res.title
this.price = res.price
this.userName = res.userName
this.status = res.status
// ...
Copy the code

Generally speaking, a commonly used page, the page may need more than ten data, then according to this logic needs to apply for more than ten local variables, after the data back nothing, directly to the ten local variables to assign a value, so a long string of assignment statements will take up the majority of the screen

I’m not a big fan of that

The first is that it is too tedious to write this method. It is necessary to define a dozen variables first and then assign values to them one by one. If the interface data structure changes during subsequent maintenance, the definition and assignment of variables will also change, which is completely unnecessary

Second, it’s not a good habit from a maintenance point of view, because if I look at the status variable, I have to figure out where it’s coming from, and then I have to figure out where I’ve changed it, it’s not clear what status does, right

My habit is to use a variable such as baseData directly to carry over the data: this.baseData = res.data, and then when I want to use one of the data, such as status, I just use Basedata.status

Variable is used for a pointer to the data, for the computer, as long as the data is clear, so it does not matter what is the variable pointing to the data, but to maintain code developers, variable should not only carry the data, it is best to have its specific meanings, such as giving up a self explanatory variables, in addition to this, it can also be further, Give variable names extra meaning

Every page will have a baseData. As long as you see this variable, there is no doubt that this variable stores the main data of the page returned by the interface, not some calculated or customized data. This data never changes after the first assignment. I only need the baseData variable to carry all the interface data, even if the interface data structure changes later, I don’t need to redefine and reassign the local data

Of course, this is only for the interface data that is acquired and will not be changed. If an interface data needs to be reprocessed several times later, or has a specific role and meaning, it is better to define a separate variable to carry it, which is also a trade-off

Abnormal logic and major variables and methods should be well commented

A lot of people don’t like to write comments. I didn’t like to write comments when I first graduated and thought it was a waste of time, but I’ve long since changed my mind that necessary comments are essential

Of course, I don’t want to encourage excessive comments. Every line of code has a line of comments, which is too much, not fiction, and comments should be explanatory, not descriptive. For example, the following comments are descriptive and unnecessary.

// Assign the sum of b and c to a
const a = b + c
Copy the code

This comment is like taking off your pants and fart, because anyone who knows how to write code can see what this line of code does

Examples of good explanatory comments:

// -1 is to smooth out any possible 1px distance deviation
this.isfilterFixed = scroll2Top() >= (filterDomTop - 1)
Copy the code

This comment is good, because the -1 appears so obtuse that it would be confusing to the inexperienced at first glance, but why end up with -1? No, -1 doesn’t seem to be a logical problem, so the comment on the code just in time solves the problem

Minus one here is what’s called abnormal logic

An iterative project for a long time, must exist in order to achieve a certain function of some kind of compromise or hack, the result will certainly lead to the appearance of the informal logic code, and you can be sure that quantity is less, add annotations to the informal logic, to avoid the subsequent nd confusion trip, more avoid inadvertently may touch the bug

In addition, some commonly used data and methods on the page should also be annotated. For example, for a VUE component, I am now in the habit of annotating every data and methods:

How’s that? Does it look tedious?

This writing method was actually required by a group leader who led me to do so, I was also disgusted at the beginning, I wrote self-explanatory code, why write so many comments? But as I suppressed my discomfort for a while, I began to appreciate it more and more

First of all, the data and methods of a component will not be too many (as long as you know how to divide components correctly), so in fact, it is not much to write notes for each data and each method, but the benefits will be considerable. Of course, these are potential follow-up benefits, not immediately reflected benefits. It’s like planting trees for generations to enjoy the shade

I try to make sure the variable name self-explanatory, and gives each variable written comments, further defined variables, is not only a subsequent took over, even if I write my own code, when see a variable, you don’t have to think much at all, according to the function of hint of the editor is directly know this variable is stem what of, What if it’s clear that there’s no need to stop and figure out what the variables are doing, and just write code that’s cool, and the person who takes it looks cool

Vue and React have a lot of comments, and some of them have a lot of comments. Vue and React have a lot of comments, and some of them have a lot of comments. They don’t understand code self-interpretation? Why don’t you go teach them?

ReactIn the corner of the source code

The selector name, preferably with a special tag

At least for now, right before and will want to write a page for a long time stage, when you one day find a data on a page or style shows a bit of a problem, then you open the page in the chrome, select the element selector name, such as the title, then the global search in the project code, suddenly found the dozens of title, So you have to locate further to the corresponding page components, on this page component search, the results you found this page components and is divided into several sub components, and then there are a dozen title, so you have to continue to orientate subcomponents, continue to search, found that even in this is the component or several title, no way out, We’re gonna have to do a visual screening

What should have been a one-step operation is suddenly cut off into several steps, which is not only time-consuming and exhausting, but also very uncomfortable

Therefore, it is best to avoid title, box, and bottom names that are too generic. Consider prod-title, user-box, and bTN-bottom names that are more specific. Of course, it is not necessary to make your class names as long and precise as possible. If you add one more qualifying letter, you can actually reduce the number of class names by a large margin. This is mainly for searching purposes, not for lengthening the class name, so you can write the class name longer, but it is not desirable if you use this form:

.page {
  &-user {
    &-box {
      &-name {
      }
    }
  }
}
Copy the code

Page-user-box-name = page-user-box-name = page-user-box-name = page-user-box-name = page-user-box-name = page-user-box-name = page-user-box-name Only page, user, box, name and other separated words can be found in the search, and there is no doubt that there are many general letters in the whole world

For this kind of subclass name and parent class name highly coupled writing method, anyway, I am deeply hated, not only search difficult search, is the naked eye to find it is difficult to find, than directly the general word as a class name practice also abhorrent, of course, write people is very cool

conclusion

For three years and the following technical personnel, is the most important thing is how to write code, and at the time of writing more thinking, the same I last time is how to achieve a demand, what went wrong, so this time have a better solution to avoid this problem, think twice before improved, if the same demand, Your implementation plan is the same as it was a year ago, and all the code you’ve written in the meantime is just piling up

I have seen too many people who work for three or five years and have only one year of work experience. If they do not lay a solid foundation while they are energetic after graduation, how can they compete with others in the second half of the career?