By Matt Maribojoc

Like it and see. Make it a habit

In this paper,GitHub Github.com/qq449245884…Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.

As VueJS became more widely used, several best practices emerged and became the standard. In this article, we will mainly share some useful resources and skills in daily development, so let’s get started.

1. In all the timev-forThe use of:key

Using the key attribute in conjunction with the V-for instruction keeps the program constant and predictable when data needs to be manipulated.

This is necessary so that Vue can keep track of component state and have a constant reference to different elements. Keys are useful when using animations or Vue transformations.

Without a key, Vue just tries to make DOM as efficient as possible. This might mean that the elements in v-for might be out of order, or they might behave unpredictably. If we have a unique key reference for each element, we can better predict how exactly a Vue application will handle DOM operations.

<! <div v-for='product in products'> </div> <! <div v-for='product in products' :key='product.id'>Copy the code

Use dash names in events

When issuing custom events, it is best to name them with a dash because we use the same syntax to listen for the event in the parent component.

So, to ensure consistency between our components, and to make your code more readable, stick to dash names in both places.

This.$emit('close-window') // < popup-window.close-window ='handleEvent()' />Copy the code

3. Declare the props in camel form and use a dash name in the template to access the props

The best practice is simply to follow the conventions of each language. In JS, hump declarations are standard, and in HTML, dash names. Therefore, we use them accordingly.

Fortunately, Vue already provides conversions between hump declarations and dash names, so we don’t have to worry about anything other than actually declaring them.

<PopupWindow titleText='hello world' /> props: {'title-text': <PopupWindow title-text='hello world' /> props: {titleText: String}Copy the code

4. Data should always return a function

When declaring component data, the data option should always return a function. If an object is returned, the data is shared between all instances of the component.

Data: {name: 'My Window', articles: []}Copy the code

Most of the time, however, our goal is to build reusable components, so we want each component to return a unique object. We do this by returning data objects in functions.

Data () {return {name: 'My Window', articles: []}}Copy the code

5. Don’t use the same element at the same timev-ifandv-forinstruction

To filter elements in an array, it is easy to use both v-if and V-for on the same element.

<div v-for='product in products' v-if='product. Price < 500'>Copy the code

The problem is that the V-for directive is preferred to the V-IF directive in Vue. It loops through each element and then checks the V-if condition.

this.products.map(function (product) {
  if (product.price < 500) {
    return product
  }
})
Copy the code

This means that even if we want to render only a few elements in the list, we have to traverse the entire array.

It certainly won’t do us any good.

A more clever solution would be to iterate over a calculated property, which would reconstitute the above example as follows:

<div v-for='product in cheapProducts'>
 
computed: {
  cheapProducts: () => {
    return this.products.filter(function (product) {
      return product.price < 100
    })
  }
}
Copy the code

This has several benefits:

  • Rendering is more efficient because we don’t iterate over everything

  • The filtered list is reused only when the dependency changes

  • This helps separate the component logic from the template and makes the component more readable

Verify our props with the correct definition

Yes, this one is important. Why?

When designing large projects, it’s easy to forget the exact format, type, and other conventions for props. If you’re on a larger development team, your colleagues won’t be mind readers, so make it clear to them how to use your components.

Therefore, we just need to write the props validation instead of laboriously tracing the components to determine the format of the props

View this example from the Vue documentation.

props: { status: { type: String, required: true, validator: function (value) { return [ 'syncing', 'synced', 'version-conflict', 'error' ].indexOf(value) ! == -1}}}Copy the code

7. Use a hump or dash for the full name of the component

The common naming convention for components is to use a hump or dash. No matter what we use, the most important thing is to be consistent. I think the hump works best because most IDE autocomplete features support it.

Vue myComponent.vue myComponent.vue mycomponent.vueCopy the code

8. Base components should be prefixed accordingly

According to the Vue style guide, a base component is a component that contains only the following:

  • The HTML element
  • Additional base components
  • Third-party UI components

The best practice for naming these components is to provide them with prefixes Base, V, or App. Again, any of these can be used as long as we are consistent throughout the project.

BaseButton.vue
BaseIcon.vue
BaseHeading.vue
Copy the code

The purpose of this naming convention is to group the base components alphabetically in the file system. In addition, by using the Webpack import feature, we can search for components that match the naming convention pattern and automatically import all components as global variables in the Vue project.

Singleton component names should be prefixedThe

Like base components, single-instance components (used once per page and accepting no prop) should have their own naming convention. These components are specific to our application, usually footer, Header, or SIDER.

This component can have only one active instance.

TheHeader.vue
TheFooter.vue
TheSidebar.vue
ThePopup.vue
Copy the code

10. Keep abbreviations consistent

A common technique among Vue developers is to use abbreviations for instructions. Such as:

  • @isv-onThe shorthand
  • :v-bindThe shorthand
  • #v-slotThe shorthand

It’s good to use these abbreviations in your Vue project. But creating certain conventions throughout the project, always using them or never using them, makes our project more cohesive and readable.

11. Do not call methods in “created” and “watch”

A common mistake Vue developers make is that they unnecessarily call methods in Created and Watch. The idea behind this is that we want to run Watch as soon as the component is initialized.

Created: () {this.handlechange ()}, methods: { handleChange() { // stuff happens } }, watch () { property() { this.handleChange() } }

However, Vue provides a built-in solution for this, which is the Vue Watch property we often forget.

All we need to do is reorganize watch slightly and declare two properties:

1. Handler (newVal, oldVal)- This is our Watch method itself. 2. Immediate: true- If declared in wacth, the handler method will be executed immediately. If false, it will not be executed at binding time

{handleChange() {// Stuff happens}}, watch () {property {immediate: true handler() { this.handleChange() } } }Copy the code

12. Template expressions should only have basic JS expressions

It is natural to add as much inline functionality as possible to the template. But this makes our templates less declarative and more complex, and makes templates very confusing.

To that end, let’s look at another example of a normalized string from the Vue style guide to see how messy it is.

{{fullname.split (' ').map(function (word) {return word[0].toupperCase () + word.slice(1)}).join(' ')}}Copy the code

Basically, we want everything in the template to be straightforward. To preserve this, we should refactor complex expressions into appropriately named component options.

Another benefit of separating complex expressions is that these values can be reused.

{{normalizedFullName}} The complex expression has been moved to a computed property computed: { normalizedFullName: function () { return this.fullName.split(' ').map(function (word) { return word[0].toUpperCase() + word.slice(1) }).join(' ') } }Copy the code

conclusion

These are the 12 most common best practices that will make our Vue code easier to maintain, more readable, and more professional. I hope you found these tips useful (because they are definitely something I always want to remember).


The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: medium.com/better-prog…

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.