This article is an object-oriented developer with some experience in Vue.js programming. If anyone needs an article on the Vue.js primer series, let me know in the comments section and write about it whenever you have time.

For most people, mastering the basic Vue.js APIs will be enough to develop front-end websites normally. But if you want to use Vue more effectively and become a Vue.js master, then I’m going to teach you the following five tips that you need to learn.

First tip: Watchers

Scene Restore:

created(){
    this.fetchPostList()
},
watch: {
    searchInputValue(){
        this.fetchPostList()
    }
}

When we create a component, we get the list once, and at the same time we listen to the input box, and every time there is a change, we get the filtered list again. This scenario is very common, is there any way to optimize it?

First, on Watchers, we can use the literal name of the function directly. Second, declare immediate:true to execute once the component is created.

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

Second tip: 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"
  @keydown.enter="search"
/>
<BaseButton @click="search">
  <BaseIcon name="search"/>
</BaseButton>

We wrote a bunch of basic UI components, and then every time we needed to use them, we had to import and declare Components. It was tedious! Uphold the principle of laziness on the lazy, we want to find ways to optimize!

We need to create our own context using the require.context() method with the help of the Webpack tool, so that the component is required automatically and dynamically. This method takes three arguments: the folder directory to be searched, whether it should also be searched for subdirectories, and a regular expression to match the files.

We add a file called global.js to the Components folder where we dynamically package all the basic components we need using Webpack.

import Vue from 'vue' function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1) }  const requireComponent = require.context( '.', false, Var component.keys ().foreach (fileName => {const componentConfig = "componentConfig").component.keys ().foreach (fileName => {const componentConfig =" requireComponent(fileName) const componentName = capitalizeFirstLetter( fileName.replace(/^\.\//, '').replace(/\.\w+$/, "") // Because the filename format is: '. / baseButton. Vue ', so here we go to turn around and tail, only keep the real name) Vue.com ponent (the componentName, componentConfig. Default | | componentConfig)})

Finally, we import ‘components/global.js’ in main.js, and then we can use these basic components anytime and anywhere without having to import them manually.

Third: Router Key

Scenario Restore: The following scenario really broke the hearts of a lot of programmers… VUE – Router is used by default for routing control. Let’s say we’re writing a blog site, and the requirement is to jump from /post-page/a to /post-page/b. And then we were surprised to find that the data didn’t update after the page jump. Right? ! The reason is that the Vue-Router “intelligently” realizes that this is the same component, and it decides to reuse it, so the method you wrote in the created function is never executed. The usual solution is to listen for a change in $route to initialize the data, as follows:

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

  }
}

The bug is fixed, but it’s not elegant to write like this every time, is it? In keeping with the principle of being lazy when you can, we want the code to look like this:

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

Analysis of moves:

To do this, add a unique key to the Router View, so that even if the URL of a common component changes, the component will always be recreated. You lose a bit of performance, but you avoid infinite bugs. Also, notice that I’m killing two birds with one stone by setting the key directly to the full path of the route.

<router-view :key="$route.fullpath"></router-view>

Fourth recruit: omnipotent render function

Scenario Restore: Vue requires each component to have only one root element. If you have multiple root elements, Vue will give you an error

<template>
  <li
    v-for="route in routes"
    :key="route.name"
  >
    <router-link :to="route">
      {{ route.title }}
    </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.

There is, but in this case we need to use the render() function to create the HTML instead of template. The nice thing about generating HTML with JS is that it’s extremely flexible and powerful, and you don’t have to learn to use Vue’s limited API directives, such as V-for and V-if. (ReactJS discards template entirely.)

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

Step 5: No move wins a move to the higher order components

When we write a component, we usually need to pass a series of props from the parent component to the child, and the parent component listens for a series of events from the child emit. For example:

< baseInput :value="value" label=" password "@Input ="handleInput" @Focus ="handleFocus> </ baseInput > <template bb0 <label> {{label}} <input :value="value" :placeholder="placeholder" @focus=$emit('focus'); $event)" @input="$emit('input', $event.target.value)" > </label> </template>

There are several optimization points as follows:

1. For each function that is passed from parent to child, we must explicitly declare it in the child props to use it. As a result, our child components will have to declare a bunch of props every time, whereas DOM-native properties like placeholer can be passed directly from parent to child without declaring them. Here’s how:

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

$attrs contains property bindings (except class and style) in the parent scope that are not recognized (and captured) as prop. When a component does not declare any prop, this contains all the bindings for the parent scope, and can be passed to the internal component via v-bind=”$attrs” — useful when creating higher-level components.

$emit(‘focus’, $event) =$emit(‘focus’, $event); $emit(‘focus’, $event) =$emit(‘focus’, $event);

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

$Listeners include the v-on event listeners in the parent scope (without the.native modifier). It can be passed in to internal components via v-on=”$Listeners “– useful for creating higher-level components.

3. Note that since our input is not the root of the BaseInput component, by default the parent scoped feature bindings that are not known as props will be “rolled back” and applied to the root element of the child component as normal HTML features. So we need to set inheritAttrs:false so that the default behavior is removed and the above two optimizations can succeed.


At the end

Master the above five tips, and you’ll be free to ride in the sea of vue.js. Go for it, boy. Some other moves may be updated in the future, so stay tuned.

If you’re interested in how Vuejs or ReactJS’s virtual DOM is implemented, check out my series of articles: With React, you can build a Virtual DOM from scratch. With React, you can build a Virtual DOM from scratch. With React, you can build a Virtual DOM from scratch.

The title is React progression, but VUEJS has actually used the virtual DOM since 2.0. Although you can still write code using VUEJS template, the template will essentially be complile into the virtual DOM. VUEJS Rendering Functions & JSX.

Advertising time: Alibaba e-commerce board one of the fastest growing new business internal recruitment, please recommend more or self-recommendation, internal recommendation priority interview, technical interview results within a week. You can send me a private email for more details, or you can send your resume to me directly at [email protected]