Betterprogramming. Pub /5-principle…

In coding, it is important to write code that is clear and understandable. Clear code is like a fine wine: it doesn’t show immediate advantages, but it still makes sense to people who read it over time, which is the biggest advantage.

Some of the code is written with low cohesion and logic, like spaghetti. You can sort out the messy logic at the time, but wait three months, five months, or 20 months to look at the code, and it’s going to be pretty bad.

As a programmer, I adhere to an important principle when programming (including vUE projects), which I call the DRY principle.

DRY is short for Don’t Repeat Yourself, which means reducing repetitive logic in programming.

The reason for sticking with the DRY principle is that when you write the same piece of logic more than twice, you get more complicated. Here’s a simple example:

You copy a piece of code in your code to a different place. What do you do when you or another programmer wants to refactor that piece of logic? You have to refactor two places. This leads to several new problems:

  • You only made one change and forgot the other
  • You modified the code and changed everything that was copied. But you notice that there are five changes.
  • You haven’t written the project in five months, and then suddenly you have to come back and fix the code. Do you remember this code being copied to multiple places?

If you write code that is clear enough you can avoid a lot of problems and save a lot of time. Not necessarily effective in the short term, but in the long run, logical code can improve coding efficiency.

Use Mixins

Mixins are the main way to reuse methods, data attributes, computed attributes, and so on in Vue.

If you have reusable logic between different components, it is best to extract that logic and share it through mixins.

Suppose your project has multiple routes and uses vue-Router to associate each route with the corresponding component.

- App.vue
-- Home.vue
-- Analytics.vue
-- Reports.vue
Copy the code

Suppose you now have a product navigation component that you want to have on all your pages.

If you don’t use mixins but want the product navigation to appear on all pages, copy the same code to mounted for each page component and add the startProductTour method to each page component. I wrote the home.vue sample here, and then you need to copy the code into Analytics. Vue and Reports.

Home.vue

export default {
  mounted() {
    this.startProductTour();
  }.
  methods: {
    startProductTour() {
      // start product tour actions here
    }
  }
}
Copy the code

But if you take that logic out and use mixins…

**ProductTour** mixin

export default {
  mounted() {
    this.startProductTour();
  }.
  methods: {
    startProductTour() {
      // start product tour actions here}}}Copy the code

… With a single line of code, you can use it in all components. Also, if you change the code, you only need to update the mixin once instead of editing multiple files.

Home.vue

import ProductTourMixin from '.. /mixins/ProductTourMixin'; export default { mixins: [ProductTourMixin] }Copy the code

In this case, your new project structure would look like this:

- App.vue
- mixins/ProductTourMixin
-- Home.vue
-- Analytics.vue
-- Reports.vue
Copy the code

This example demonstrates that mixins make code logic clearer and follow the DRY principle. This will save you time and energy to deal with a headache

Try to split Components

When I first wrote code in VUE, one of my VUE components had hundreds to tens of thousands of lines of code. This huge component contains a lot of logic, with huge HTML

  • The code I write is not reusable.
  • This code becomes more and more difficult to read and maintain over time
  • It is difficult to divide labor and conflict when working with colleagues.

This convinced me of one thing — creating one or several large components instead of many small ones is an absolute nightmare.

So what’s the advantage of creating many small components instead of fewer large ones?

  1. Small components are often reusable, saving time and avoiding duplicate code.
  2. In most cases, you are logically separating parent and child elements. If you change the child component, the parent element is not affected. The same is true if you modify the parent, as long as you don’t modify the props that the parent passes to the child.
  3. Smaller components have a performance advantage in large V-for loops because Vue does not update them unless the props change (props of non-object types).

For large projects, it is necessary to break the entire project into components to make the development process more manageable.

This quote from the official Vue documentation explains the importance of breaking projects into components.

** Tip: ** Reading the technical documentation of your favorite framework can be informative, so I recommend reading it often.

Add Validate to Props

Validation props is a way to make your Vue application more maintainable.

Let’s look at an incorrect use of props:

export default {
  props: ['myProp'],}Copy the code

This way of defining props is only possible during development, but you should write a complete definition for props before going live. At the very least, you should define a type for props.

// quick way
export default {
  props: {
    myProp: String,}}// this should be preferred
export default {
  props: {
    myProp: {
      type: String}}}Copy the code

But the best way is to have a complete definition of props and add validation logic.

props: {
  myProp: {
    type: Number.required: true.validator: (value) = > {
      return value > 0; }}}Copy the code

If you write the validation logic for props to handle unexpected situations when an unexpected value is passed in.

Another advantage is that by defining explicit props, you can look at the definition and validation logic of props to understand the expected values. You can think of props as a small document that we know about this component. When coding, it is better to define input rules and name the semantically correct code rather than write comments.

Again, logical code is better than messy code. It keeps the types of props in mind and reduces errors during coding.

Decouple the view layer from the data layer

Unlike Angular, Vue does not provide the logic of the data layer. You need to write your own data layer to request data from the interface in the background and return it to Vue for rendering.

In my experience, try to separate the view layer from the data layer.

To better illustrate my point, I will give an example. Suppose you have a Reports component that contains three subcomponents: ReportTable, ReportChart, and ReportStats.

Reports.vue

<! -- This example is intentionally kept simple --><template>
  <report-stats :stats="stats" />
  <report-chart :chartData="chartData" />
  <report-table :breakdown="breakdown" />
</template>
<script>
export default {
  data() {
    return {
      stats: null.chartData: null.breakdown: null}}}</script>
Copy the code

This is the infrastructure for your Reports component. Now, you need to get the data from the API, so you’ll write the following code:

mounted() {
  this.getStats();
}
Copy the code

Next, write getStats:

methods: {
  getStats() {
    axios.get('/api/to-get/the-data')
      .then(response= > {
        this.stats = response.data.stats }); }}Copy the code

That’s fine for now, and it might be fine for smaller projects. However, there are many benefits to separating the data layer from the view layer:

  • The interface layer is likely to be reused in a back-end environment. Or if the front end does not use the Vue project and is built with another framework, the interface layer is still preserved.

  • Helps you keep Vue code logical and easy to understand. Because the view layer doesn’t need to know the complex logic of the data layer.

  • Having a well-defined API layer, sort of like a pre-controller, helps you and your team understand what parameters are required for those interfaces and how each interface is called.

So, how do we rewrite our code?

ReportsService.js

const ReportsService = {
  stats: {
    index: async (/* params */) = > {const response = await axios.get('/api-link');
      returnresponse.data; }}}export default ReportsService;
Copy the code

Reports.vue

import ReportsService from '.. /services/ReportsService'; export default { methods: { async getStats() { this.stats = await ReportsService.stats.index(/* params */); }}}Copy the code

We used simple logic to create a service that could interact with our back-end apis or implement data-layer logic. Then, our Vue components don’t need to know more about our API or data layer and get the data they need directly from the services we create.

Code according to the Vue Style guide

An in-depth discussion of vUE’s style guide is beyond the scope of this article. However, it’s also important for developers to learn how the framework is designed and how the framework wants you to use it.

The creator of the framework lays down some standard coding guidelines that community members follow when using the framework.

Some important coding specifications are listed below:

Use the data() function instead of a data object

Example:

export default {
  data: {
    value: 1,}}Copy the code

Good examples:

export default {
  data() {
    return {
      value: 1,}}}Copy the code

Why use a data() function instead of a Date object? When the value of data is an object, it is shared between all instances of the component. When A component is reused by A and B, the modification of component data in A affects component B.

Add key to V-for

With V-for, you need to add a key because it helps vue identify unmodified components in dom-diff and reuse them to improve rendering efficiency.

<my-item
  v-for="item in items"
  :key="item.id"
  :item="item"/ > <! -- orwith HTMl elements -->
<div
  v-for="item in items"
  :key="item.id"
>
  {{ item.value }}
</div>
Copy the code

Avoid v-if and V-for

The VUE documentation clearly states why. This is not done because Vue renders only a small part of the data and has to traverse the entire list each time it rerenders.

Here’s an example to prove it:

Example:

<div v-for="item in items" v-if="item.shouldShow()">
  {{ item.value }}
</div>
Copy the code

Good examples:

<div v-for="item in visibleItems">
    {{ item.value }}
</div>
Copy the code

And add the following attributes in compued:

visibleItems() {
  return this.items.filter(item= > {
    return item.shouldShow();
  });
}
Copy the code

The benefits of this are as follows:

  1. Calculate attributevisibleItemsOnly when theitemsRecalculation occurs when there is a change.
  2. v-forDeal only withvisibleItemsNot the wholeitemsArray, which makes rendering more efficient.
  3. The logic in the template is cleaner and clearer. Roger decouples the render layers, making the code more maintainable.

For more information on coding styles, you can read the Official Section of the Vue Documentation. Even if you are already an experienced Vue developer, you can still learn a lot from it.

conclusion

Writing code that is clear and easy to understand will make your colleagues and you more pleasant to work with. You’re also lucky you don’t have to maintain a lot of spaghetti-like code anymore.

If you are working on a CodeView, you can evaluate your code according to the five principles above so that your team can contribute high quality, efficient code.

Thanks for reading this article!

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign