Detailed explanation of Vue.js practical cases
May 12, 2018 pm 03:00 PMThis time I will bring you a detailed explanation of Vue.js practical cases. What are the precautions when using Vue.js practical cases. The following is a practical case, let’s take a look.
For most people, after mastering a few basic APIs of Vue.js, they 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() ??} }
We get it when the component is created It is very common to list once, monitor the input box at the same time, and re-obtain the filtered list every time there is a change. 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 ??} }
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 ?} } <BaseInput v-model="searchText" @keydown.enter="search" /> <BaseButton @click="search"> ?<BaseIcon name="search"/> </BaseButton>
We wrote a bunch of basic UI Components, and every time we need to use these components, we must first import and then declare the components, which is very cumbersome! 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 components . This method requires 3 parameters: the folder directory to be searched, whether its subdirectories should also be searched, and a regular expression that matches the file.
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',?所以這里我們?nèi)サ纛^和尾,只保留真正的文件名 ?) ?Vue.component(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 manually introducing them.
Third move: Router key that removes all the firepower
Scene restoration:
The following scene really breaks the hearts of many programmers... Let’s use it by default first It is Vue-router that implements 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 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 solved, but is it too inelegant to write like this every time? Adhering to the principle of being lazy if you can, 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)?{ ??//?... ?} }
Move analysis:
So how can we achieve such an effect? ??The answer is to add a router-view unique key, 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>
The fourth trick: the omnipotent render function
Scene restoration:
vue requires every component There can only be one root element. When you have 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.
Move analysis:
Is there any way to resolve it? The answer is yes, but at this time we You 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 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> ?) }
Fifth move: No move to win high-level components with a move
Key point: this One move has infinite power, be sure to master it
當(dāng)我們寫組件的時候,通常我們都需要從父組件傳遞一系列的props到子組件,同時父組件監(jiān)聽子組件emit過來的一系列事件。舉例子:
//父組件 <BaseInput :value="value" label="密碼" placeholder="請?zhí)顚懨艽a" @input="handleInput" @focus="handleFocus> </BaseInput> //子組件 <template> ?<label> ??{{?label?}} ??<input :value="value" :placeholder="placeholder" @focus=$emit('focus', $event)" @input="$emit('input', $event.target.value)" > ?</label> </template>
有下面幾個優(yōu)化點:
1.每一個從父組件傳到子組件的props,我們都得在子組件的Props中顯式的聲明才能使用。這樣一來,我們的子組件每次都需要申明一大堆props, 而類似placeholer這種dom原生的property我們其實完全可以直接從父傳到子,無需聲明。方法如下:
<input :value="value" v-bind="$attrs" @input="$emit('input', $event.target.value)" >
$attrs 包含了父作用域中不作為 prop 被識別 (且獲取) 的特性綁定 (class 和 style 除外)。當(dāng)一個組件沒有聲明任何 prop 時,這里會包含所有父作用域的綁定,并且可以通過 v-bind="$attrs" 傳入內(nèi)部組件——在創(chuàng)建更高層次的組件時非常有用。
2.注意到子組件的 @focus=$emit('focus', $event)"
其實什么都沒做,只是把event傳回給父組件而已,那其實和上面類似,我完全沒必要顯式地申明:
<input :value="value" v-bind="$attrs" v-on="listeners" > computed:?{ ?listeners()?{ ??return?{ ???...this.$listeners, ???input:?event?=>? ????this.$emit('input',?event.target.value) ??} ?} }
$listeners 包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽器。它可以通過 v-on="$listeners" 傳入內(nèi)部組件——在創(chuàng)建更高層次的組件時非常有用。
3.需要注意的是,由于我們input并不是BaseInput這個組件的根節(jié)點,而默認(rèn)情況下父作用域的不被認(rèn)作 props 的特性綁定將會“回退”且作為普通的 HTML 特性應(yīng)用在子組件的根元素上。所以我們需要設(shè)置 inheritAttrs:false ,這些默認(rèn)行為將會被去掉, 以上兩點的優(yōu)化才能成功。
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注php中文網(wǎng)其它相關(guān)文章!
推薦閱讀:
The above is the detailed content of Detailed explanation of Vue.js practical cases. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Vue.js is not difficult to learn, especially for developers with a JavaScript foundation. 1) Its progressive design and responsive system simplify the development process. 2) Component-based development makes code management more efficient. 3) The usage examples show basic and advanced usage. 4) Common errors can be debugged through VueDevtools. 5) Performance optimization and best practices, such as using v-if/v-show and key attributes, can improve application efficiency.

Vue.js is mainly used for front-end development. 1) It is a lightweight and flexible JavaScript framework focused on building user interfaces and single-page applications. 2) The core of Vue.js is its responsive data system, and the view is automatically updated when the data changes. 3) It supports component development, and the UI can be split into independent and reusable components.
