SoFunction
Updated on 2025-04-04

Best Practice (Five Tips to Help You Become a Vuejs Master)

This article is aimed at developers with certain programming experience. If anyone needs an introduction to the series of articles, you can tell me in the comment section and write them to you if you have time.

For most people, after mastering several basic APIs, they can already develop front-end websites normally. But if you want to use Vue more efficiently to develop and become a master, then you must study these five tricks I want to teach below.

The first trick: Watchers that simplify the complexity

Scene Restore:

created(){
  ()
},
watch: {
  searchInputValue(){
    ()
  }
}

When the component is created, we get the list once and listen to the input box at the same time. Whenever there is a change, it is common to re-get the filtered list again. Is there a way to optimize it?

Tactic analysis:

First, in watchers, you can directly use the literal name of the function; secondly, declaring immediate:true means that it is executed immediately when creating a component.

watch: {
  searchInputValue:{
    handler: 'fetchPostList',
    immediate: true
  }
}

The second trick: once and for all component registration

Scene Restore:

import BaseButton from './baseButton'
import BaseIcon from './baseIcon'
import BaseInput from './baseInput'
export default {
 components: {
  BaseButton,
  BaseIcon,
  BaseInput
 }
}
<BaseInput
 v-model="searchText"
 @="search"
/>
<BaseButton @click="search">
 <BaseIcon name="search"/>
</BaseButton>

We have written a bunch of basic UI components, and every time we need to use these components, we have to import first and then declare components, which is very cumbersome! Adhering to the principle of being lazy as long as you can, we must find ways to optimize!

Tactic analysis:

We need to use the magic webpack to create our own (module) context using the () method to achieve automatic dynamic require components. This method requires 3 parameters: the folder directory to be searched, whether it should also search for its subdirectories, and a regular expression matching the file.

We add a file called in the components folder, and use webpack to dynamically package all the required basic components.

import Vue from 'vue'
function capitalizeFirstLetter(string) {
 return (0).toUpperCase() + (1)
}
const requireComponent = (
 '.', false, /\.vue$/
  //Find the files named after .vue under the components folder)
().forEach(fileName =&gt; {
 const componentConfig = requireComponent(fileName)
 const componentName = capitalizeFirstLetter(
  (/^\.\//, '').replace(/\.\w+$/, '')
  //Because the filename format obtained is: './', so here we remove the head and tail and only retain the real file name )
 (componentName,  || componentConfig)
})

Finally we import 'components/' , and then we can use these basic components anytime, anywhere without manual introduction.

The third trick: the router key that removes fire from the bottom of the pot

Scene Restore:

The following scene really hurts the hearts of many programmers... First, we default to using Vue-router to achieve routing control.

Suppose we are writing a blog website, and the requirement is to jump from /post-page/a to /post-page/b. Then we were surprised to find that the data was not updated after the page jumped? ! The reason is that vue-router "intelligently" discovers that this is the same component, and then it decides to reuse the component, so the method you wrote in the created function is not executed at all. The usual solution is to listen for changes in $route to initialize the data, as follows:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
}, 
watch: {
 '$route': {
  handler: 'resetData',
  immediate: true
 }
},
methods: {
 resetData() {
   = false
   = null
   = null
  (this.$)
 },
 getPost(id){

 }
}

The bug was solved, but it is too inelegant to write like this every time, right? Adhering to the principle of being lazy, we hope that the code will be written like this:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
},
created () {
 (this.$)
},
methods () {
 getPost(postId) {
  // ...
 }
}

Tactic analysis:

So how can we achieve this effect? ​​The answer is to add a unique key to the router-view, so that even if a public component is changed, the component will be recreated. (Although a little performance is lost, unlimited bugs are avoided). At the same time, note that I set the key directly to the full path of the route, killing two birds with one stone.

<router-view :key="$"></router-view>

The fourth move: The omnipotent render function

Scene Restore:

vue requires that each component can only have one root element. When you have multiple root elements, vue will report an error to you

<template>
 <li
  v-for="route in routes"
  :key=""
 >
  <router-link :to="route">
   {{  }}
  </router-link>
 </li>
</template>

 ERROR - Component template should contain exactly one root element.
    If you are using v-if on multiple elements, use v-else-if
    to chain them instead.

Tactic analysis:

Is there any way to resolve it? The answer is, but at this time we need to use the render() function to create HTML, not template. In fact, the advantage of using js to generate html is that it is extremely flexible and powerful, and you don’t need to learn the command APIs with limited functions using vue, such as v-for and v-if. (reactjs completely discards template)

functional: true,
render(h, { props }) {
 return (route =>
  <li key={}>
   <router-link to={route}>
    {}
   </router-link>
  </li>
 )
}

Fifth move: Advanced components that are better than moves without moves

Key points: This move is extremely powerful, please be sure to master it

When we write components, we usually need to pass a series of props from the parent component to the child component, and the parent component listens for a series of events coming from the child component emitted. Give an example:

// Parent component&lt;BaseInput 
  :value="value"
  label="password" 
  placeholder="Please fill in your password"
  @input="handleInput"
  @focus="handleFocus&gt;
&lt;/BaseInput&gt;
//Subcomponent&lt;template&gt;
 &lt;label&gt;
  {{ label }}
  &lt;input
   :value="value"
   :placeholder="placeholder"
   @focus=$emit('focus', $event)"
   @input="$emit('input', $)"
  &gt;
 &lt;/label&gt;
&lt;/template&gt;

There are several optimization points:

1. We must declare explicitly in the child component's props from the parent component to the child component's props. In this way, our child components need to declare a lot of props every time, and we can actually pass dom native properties like placeholer directly from the parent to the child without declaration. The method is as follows:

<input
   :value="value"
   v-bind="$attrs"
   @input="$emit('input', $)"
  >

$attrs contains attribute bindings in the parent scope that are not recognized (and obtained) as props (except class and style). When a component does not declare any props, it contains all parent scope bindings and can be passed into internal components via v-bind="$attrs" - useful when creating higher-level components.

2. Pay attention to the subcomponent @focus=$emit('focus', $event)" Actually, I did nothing, just passed the event back to the parent component. That is actually similar to the above, and I don't need to explicitly state it:

<input
  :value="value"
  v-bind="$attrs"
  v-on="listeners"
>
computed: {
 listeners() {
  return {
   ...this.$listeners,
   input: event => 
    this.$emit('input', )
  }
 }
}

$listeners contains the v-on event listener in the parent scope (excluding .native modifiers). It can be passed into internal components via v-on="$listeners" - very useful when creating higher-level components.

3. It should be noted that since our input is not the root node of the BaseInput component, by default, the feature binding of the parent scope that is not considered props will "fall back" and be applied to the root element of the child component as a normal HTML feature. So we need to set inheritAttrs:false , these default behaviors will be removed, and the optimization of the above two points will be successful.

Ending

The above is the best practices that the editor introduces to you(Five tricks to help you becomevuejsmaster),Hope it will be helpful to everyone,If you have any questions, please leave me a message,The editor will reply to everyone in time。 Thank you very much for your support for my website!