Table of Contents
The first move: Watchers that simplify complexity
Second move: Once and for all component registration
Third move: Router key that pulls out all the stops
The fourth trick: the omnipotent render function
The fifth move: No move to win high-level components with a move
结尾
Home Backend Development PHP Tutorial Vue.js best practices (five tips to make you a Vue.js master)

Vue.js best practices (five tips to make you a Vue.js master)

Mar 30, 2018 pm 01:22 PM
javascript vue.js become

This article is mainly to share with you the best practices of Vue.js, five tips to make you a Vue.js master, I hope it can help friends in need

For most people, mastering Vue After a few basic .js APIs, you can already develop front-end websites normally. But if you want to use Vue to develop more efficiently and become a Vue.js master, then you must seriously study the five tricks I will teach you below.

The first move: Watchers that simplify complexity

Scene restoration:

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

When the component is created, we get the list once and listen to the input at the same time Frame, it is very common to re-obtain the filtered list every time a change occurs. Is there any way to optimize it?

Move analysis:
First of all, in watchers, you can directly use the literal name of the function; secondly, declaring immediate:true means that it will be executed immediately when the component is created.

watch: {
    searchInputValue:{
        handler: 'fetchPostList',
        immediate: true
    }
}
Copy after login

Second move: Once and for all component registration

Scene restoration:

import BaseButton from './baseButton'
import BaseIcon from './baseIcon'
import BaseInput from './baseInput'

export default {
  components: {
    BaseButton,
    BaseIcon,
    BaseInput
  }
}
Copy after login
<BaseInput
  v-model="searchText"
  @keydown.enter="search"
/>
<BaseButton @click="search">
  <BaseIcon name="search"/>
</BaseButton>
Copy after login

We wrote a bunch of basic UI components, and then every time we When you need to use these components, you must first import and then declare the components, which is very tedious! Adhering to the principle of being lazy if you can, we must find ways to optimize!

Move analysis:
We need to use the artifact webpack to create our own (module) context using the require.context() method to achieve automatic Dynamic require component. This method takes 3 parameters: the folder directory to search, whether its subdirectories should also be searched, and a regular expression to match files.

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

import Vue from 'vue'

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

const requireComponent = require.context(
  '.', false, /\.vue$/
   //找到components文件夹下以.vue命名的文件
)

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = capitalizeFirstLetter(
    fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
    //因为得到的filename格式是: './baseButton.vue', 所以这里我们去掉头和尾,只保留真正的文件名
  )

  Vue.component(componentName, componentConfig.default || componentConfig)
})
Copy after login

Finally we import 'components/global.js' in main.js, then we can use these basic components anytime and anywhere without manually introducing them.

Third move: Router key that pulls out all the stops

Scene restoration:
The following scene really breaks the hearts of many programmers... First By default, everyone uses Vue-router to implement 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 surprisingly discovered that the data was not updated after the page jumped? ! The reason is that vue-router "intelligently" discovered that this is the same component, and then it decided to reuse this component, so the method you wrote in the created function was not executed at all. The usual solution is to monitor 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() {
    this.loading = false
    this.error = null
    this.post = null
    this.getPost(this.$route.params.id)
  },
  getPost(id){

  }
}
Copy after login

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

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

Move analysis:

So how can we achieve such an effect? ​​The answer is Add a unique key to router-view, so that even if it is a public component, as long as the URL changes, the component will be recreated. (Although some performance is lost, infinite 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="$route.fullpath"></router-view>
Copy after login

The fourth trick: the omnipotent render function

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

<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.
Copy after login

Move analysis:
Is there any way to resolve it? The answer is yes, but at this time we need 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 do not need to learn to use vue's instruction API with limited functions, such as v-for and v-if. (reactjs completely discards the template)

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

The fifth move: No move to win high-level components with a move

Emphasis: This move is extremely powerful, please be sure to master it
When we write components, communication between parent and child components is very important. Usually we need to pass a series of props from the parent component to the child component, and at the same time the parent component listens to a series of events emitted from the child component. For example:

//父组件
<BaseInput 
    :value="value"
    label="密码" 
    placeholder="请填写密码"
    @input="handleInput"
    @focus="handleFocus>
</BaseInput>

//子组件
<template>
  <label>
    {{ label }}
    <input
      :value="value"
      :placeholder="placeholder"
      @focus=$emit(&#39;focus&#39;, $event)"
      @input="$emit(&#39;input&#39;, $event.target.value)"
    >
  </label>
</template>
Copy after login

has the following optimization points:

1. For every prop passed from the parent component to the child component, we must explicitly declare it in the Props of the child component. can be used. In this way, our child components need to declare a lot of props every time, but for DOM-native properties like placeholer, we can actually pass them directly from the parent to the child without declaring them. The method is as follows:

    <input
      :value="value"
      v-bind="$attrs"
      @input="$emit(&#39;input&#39;, $event.target.value)"
    >
Copy after login

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

2. Notice that the child component's @focus=$emit('focus', $event)"actually does nothing. It just passes the event back to the parent component. Then In fact, similar to the above, there is no need for me to explicitly declare:

<input
    :value="value"
    v-bind="$attrs"
    v-on="listeners"
>

computed: {
  listeners() {
    return {
      ...this.$listeners,
      input: event => 
        this.$emit('input', event.target.value)
    }
  }
}
Copy after login

$listeners包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

3.需要注意的是,由于我们input并不是BaseInput这个组件的根节点,而默认情况下父作用域的不被认作 props 的特性绑定将会“回退”且作为普通的 HTML 特性应用在子组件的根元素上。所以我们需要设置inheritAttrs:false,这些默认行为将会被去掉, 以上两点的优化才能成功。


结尾

掌握了以上五招,你就能在Vue.js的海洋中自由驰骋了,去吧少年。
陆续可能还会更新一些别的招数,敬请期待。

相关推荐:

Vue.js之CLI框架安装步骤

Vue.js如何实现真分页

Vue.js自定义事件如何进行表单输入组件

The above is the detailed content of Vue.js best practices (five tips to make you a Vue.js master). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles