Original address:
Vue. Js Best practices ✓ — Noteworthy – The Journal Blog


Riccardo Polacci


Translator: amandakelake

Hello, developers!

After studying the official VueJs documentation and other vUE resources on the web, I have compiled a list of best practices and style guidelines to help you write vUE code that is more correct and more acceptable to your peers.

The following points are related to some features/optimizations, while others are related to VueJs naming conventions and element sorting. More details can be found directly in the summary at the bottom.


Clear event listeners with $off when the component is destroyed

When using $on for event listening, remember to remove event listening with $off in the destroyed() hook to prevent memory leaks.

Name events with a dash delimited form

When triggering/listening for custom events, you should always separate them with a dash. Why is that? The event name is automatically converted to a dash delimited form anyway. Instead of naming listener events with a hump or a capital letter, use a more clear and meaningful way to declare an event: a dash separation

// Emitting
this.$emit('my-event') // instead of myEvent
// Listening
v-on:my-event
Copy the code

Do not call the same method in the Created lifecycle and watch

If we need to call the same method when the component initializes and listens for property changes, we would normally do something like this

watch: {
  myProperty() { this.doSomething(); }},created() {
  this.doSomething();
},
methods: {
  doSomething() {
     console.log('doing something... '); }},Copy the code

While the above code looks fine, the method executed inside the Created hook is redundant. We can put the methods we need to execute in watch to avoid repeating code in the Created hook, which will fire one more time when the component is instantiated. For example:

watch: {
  myProperty: {
    immediate: true.// This callback will be invoked immediately after the listening starts
    handler() {
      this.doSomething(); }}},methods: {
  doSomething() {
     console.log('doing something... '); }},// Better solution
watch: {
  myProperty: {
    immediate: true,
    handler() {
      console.log('doing something... '); // Methods that are only used once need not be declared in methods}}},Copy the code

Don’t forget to use keys in v-for loops

The most common approach is to always add the :key key to the template loop. None: The V-for loop for the key key can be troublesome in error location, especially animation related

Use $_ as a prefix for mixins’ private properties

Mixins are a great way to reuse code, combining duplicate code into a single module that can then be introduced as needed. But (most likely) something will go wrong. Next, let’s focus on solving the problem of duplicate attribute name conflicts.

When we mix mixins into components, that is, merging the code in the mixin with the code in the component itself, what happens when we encounter properties with the same name? The higher the component priority, the higher the component properties.

What if I want to make mixin code a higher priority? We cannot assign priority, but we can avoid attribute overlap or overwriting with proper naming conventions.

To distinguish mixin attributes from component attributes, we usually use ‘$_’ as the attribute prefix. Why? The main reasons are as follows:

  1. Suggestions from the VueJs Style Guide
  2. Vue use_Prefix to define its own private property

  3. $Are specific instance attributes that the Vue ecosystem exposes to users

In the style guide — vue.js, they suggest adding a mixin attribute name like this: $_myMixin_updateUser

As opposed to readability, I’ve found that adding names to mixins can sometimes lead to confusion. But it also depends on the mixin code itself, the special case, or the developer.

By adding a simple $_, like $_updateUser, the code becomes more readable and can easily distinguish component private properties from mixin properties.

Methods or properties used in mixins should be read directly in mixins

Following the mixin point, there is another point to note.

Suppose we create a mixin that uses the this.language property, but the property is not defined or retrieved inside the mixin, then components that mixin the mixin must include the language property.

As you already know, this is very error-prone. To avoid errors ahead of time, it is best to define and retrieve properties or methods used in mixins only. You don’t have to worry about getting a property twice, because VueJs is smart about this, and if it detects a property twice, it will handle it automatically (in most cases directly from Vuex).

Use a capital letter or dash to separate life list file components

The editor is more integrated with uppercase naming and friendlier for auto-complete/import functionality in common ides.

If we want to avoid case insensitive file systems, it is best to use a dash separator

Prefixes the underlying component name

Presentation components, pure components, should be prefixed to distinguish them from other impure components. This can greatly improve the readability of the project and the collaborative development experience of the team.

Use uppercase names to name components in JS

In JavaScript, class and stereotype constructors have a default convention to use uppercase names, which makes the same sense for Vue components. If we only use global component definitions with ‘Vue.component’, it is recommended to use a dash to separate the names

Declare prop names with hump names, but use a dash to separate names in templates

Follow the conventions of each language: JavaScript (hump) and HTML (dash split), defining prop with camel name in JS and dash split name in HTML.

Follow the order of component options in the style guide

This may seem a bit rigid, but performing the same order for all options of components throughout the project helps a lot in finding content and creating new components.

See the VueJs Style Guide here – vue.js

Do not use v-if on the same element as v-for

This is a performance killer, and the larger the list, the more it affects performance.

To see the problem in code, look at the following scenario:

<ul>
  <li
    v-for="game in games"
    v-if="game.isActive"
    :key="game.slug"
  >
    {{ game.title }}
  <li>
</ul>

Copy the code

Similar to executing the following code:

this.games.map(function (game) {
  if (game.isActive) {
    return game.title
  }
})
Copy the code

We can see here that we will have to iterate through the entire Games array, whether game.isActive has changed or not

In other frameworks like Angular, this practice is not compiled (‘ * ngIf ‘cannot enter the same element with’ * ngFor ‘).


Actions must have a return value

This has to do with async/await and Vuex actions

Look at the following examples:

// Store [SOME_ACTION] () {// do something, take a while to finish console.log()'Action done');
}
// Consuming action
async doSomething() {
  await dispatch(SOME_ACTION);
  console.log('Do stuff now');
}
This will output:
// Do stuff now
// Action done
Copy the code

This happens because await doesn’t know what to wait for, instead, if we actually return promise.resolve (), await will wait for resolution and then continue

// Store [SOME_ACTION] () {// do something, take a while to finish console.log()'Action done');
   Promise.resolve();
}
// Consuming action
async doSomething() {
  await dispatch(SOME_ACTION);
  console.log('Do stuff now');
}
This will output:
// Action done
// Do stuff now
Copy the code

Use selectors in actions and getters

When creating a selector, use it not only in your application logic, but also in the Vuex Store

It’s easier to explain in code:

// Suppose we read the following language propertiesexportconst language = (state) => state.userConfig.language; // In one of the actions, you need to use language: / / bad example [GET_GAMES] ({commit, rootState} {const lang = rootState. UserConfig. Language; // Do stuff... } // Correct example [GET_GAMES]({commit, rootState}) {const lang = language(rootState); // Do stuff... }Copy the code

conclusion

  1. Don’t forgetv-forUse in circulationkey

  2. useThe $_As amixinsThe private property prefix of

  3. mixinMethods or attributes used in themixinReads the

  4. Use a capital letter or dash to separate life list file components
  5. Prefixes the underlying component name
  6. Use uppercase names to name components in JS
  7. The statementpropUse a camel name, but use a dash to separate names in templates

  8. Follow the order of component options in the style guide
  9. Do not usev-forIs used on the same elementv-if

  10. ActionsThere must be a return value

  11. inactionsandgettersUse selectors in

source

  • https://vuejs-tips.github.io/cheatsheet/

  • https://learn-vuejs.github.io/vue-patterns/patterns/

  • https://vuejs.org/v2/style-guide/

Thank you

This article is a collaboration of several developers who are using VueJs on the same project, and following this style guide and best practices will help every new developer familiarize themselves with the project code as quickly as possible.

If you have any suggestions or better suggestions, please feel free to comment.