Vue. Js best practices ✓ — Noteworthy – The Journal Blog

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.

Used during component destruction$offClear event listening

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

Don’t increatedLife cycle andwatchCall the same method in

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...');
  }
},

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 called immediately after listening starts. Handler () {this.dosomething (); } } }, methods: { doSomething() { console.log('doing something... '); }}, // Better solution watch: {myProperty: {immediate: true, handler() {console.log('doing something... '); }}}};

Don’t forgetv-forUse in circulationkey

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

useThe $_As amixinsThe private property prefix of

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 prefix the mixin attributes with $_. Why? The main reasons are as follows: 1. Suggestions from the VueJs style guide; 2. Vue uses the _ prefix to define its own private attributes; 3

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.

mixinMethods or attributes used in themixinReads the

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 through Vue.com Ponent, we recommend using a dash to separate the names

The statementpropUse a camel name, 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 usev-forIs used on the same elementv-if

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>

Similar to executing the following code:

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

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 approach is not compiled (* ngIf cannot enter the same element with * ngFor).

ActionsThere must be a return value

This has to do with async/await and Vuex actions

Look at the following examples:

// Store [SOME_ACTION] () {// do something, take some time 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

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 some time 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

inactionsandgettersUse selectors in

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:

/ / assume we read the following language attribute export const 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... }

conclusion

  1. Used during component destruction$offClear event listening
  2. Name events with a dash delimited form
  3. Don’t increatedLife cycle andwatchCall the same method in
  4. Don’t forgetv-forUse in circulationkey
  5. useThe $_As amixinsThe private property prefix of
  6. mixinMethods or attributes used in themixinReads the
  7. Use a capital letter or dash to separate life list file components
  8. Prefixes the underlying component name
  9. Use uppercase names to name components in JS
  10. The statementpropUse a camel name, but use a dash to separate names in templates
  11. Follow the order of component options in the style guide
  12. Do not usev-forIs used on the same elementv-if
  13. ActionsThere must be a return value
  14. inactionsandgettersUse selectors in

source

  • vuejs-tips.github.io/cheatsheet/
  • Learn – vuejs. Making. IO/vue – the pattern…
  • Vuejs.org/v2/style-gu…

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.