Talk about some moves used by vue3.0 in the project - External skill chapter (I)

Please call me ames 2021-09-15 07:36:19
talk moves used vue3.0 vue


Preface

Vue3.0 In the last year 9 It was officially released in April , With some new API And the arrival of black magic , Some developers have applied it to newly created projects , Some developers have upgraded , Some are still waiting . So we won't talk about internal skills today ( Source code ), Just talk vue3.0 Your moves , How to be unique in Wulin .

One 、 Ten thousand swords belong to the emperor

The return of ten thousand swords is the highest level of swordsmanship , Once you use ten thousand swords, you will return to your family like a servant to the Lord , Like worshiping a God . When the sword moves out , The fierce and unparalleled sword strength is generated by the body , The body shape can turn into a blue smoke , Strong Qi scattered everywhere . Countless sharp swords fly like a storm . Flying all over the sky , The sword is like a net , Fierce and unparalleled , It's a wonder . You can also use ten thousand swords to attack .

All swords of swordsmanship in martial arts belong to the sect , Indicates the highest level of fencing , and vue3.0 Medium h function , Can cover all dom Tree rendering and events 、 Binding of properties .

2.1 h Rendering function Introduce

Vue It is recommended that you use templates to create your HTML. But in some scenarios , You really need JavaScript The ability to program completely . You can use Rendering function , It's closer to the compiler than the template .

2.1.1 Slot rendering

There is one named demo The components of , There is a slot name inside the component demoSlot, Use h The rendering function is written as :

2.1.2 Event binding

We must provide a correct... For the event handler prop name , for example , To deal with  click  event ,prop Name should be  onClick.

2.2 Examples of writing

import { defineComponent, h } from 'vue';
export default defineComponent({
name: 'renderDemo',
props: ['modelValue'],
setup(props, { slots, emit }) {
return () => {
return h('demo', {
// dom style
style: {},
// class Style name
class: [],
// dom Custom properties
'data-id': '123456',
// v-on、@ Instruction example
onClick: event => {
console.log('event', event);
},
// demoSlot Slot name rendering example
demoSlot: () => {
return h('div', '1111');
},
// v-model Example
modelValue: props.modelValue,
'onUpdate:modelValue': value => emit('update:modelValue', value)
})
};
},
});
 Copy code 

More to see : github.com/vuejs/rfcs/…

Two 、 Layers of falling wave palm

Layer wave superposition , Yunshulang roll , Interlocking , It goes on and on .

1.1 Recursive component rendering

const vnodeSchema = {
id: '001',
class: 'parent-class',
componentName: 'demo',
children: [
{
id: '00101',
class: 'children-class',
componentName: 'demo',
},
{
id: '00101',
class: 'children-class',
componentName: 'demo',
}
]
}
 Copy code 

The train of thought is : according to componentName name , Use resolveComponent Get the instance of the component vnode, take vnodeSchema Resolve the component properties in , Return to the real props, Last call h Rendering function , Conduct vnode Node rendering and rendering props assignment . Recursive calls can be made according to vnodeSchema Description of , Dynamic rendering dom node .

3、 ... and 、 Yin Yang Sword

Cooperation skills of Xiandu sect , Created by Taoist Huang mu , Two people make , One attack, one defense , According to the eight eight sixty-four trigrams in the book of changes , Sword birth and death , Eliminate long , There is a faint wind and thunder .

Yin Yang Sword , The purpose of the sword is to attack and defend , Circle of life , stay vue3.0 The focus of responsive data in is to read and write , Trigger the data collected in the dependency separately get、set.

3.1 Responsive data API Introduce

3.1.1 reactive

Receive an ordinary object and return the name of the ordinary object Proxy, Default deep proxy , If deep-seated agents are not needed in the project , You can use shallowReactive Improve performance .

stay Vue.js 3.0 in  reactivity  The module encapsulates the toolset of some responsive systems , It is used for boundary judgment and type conversion in the internal source code , Exporting these methods allows users to use them according to their own usage scenarios ,markRaw  and  shallowXXX  Used to skip depth proxy , for example : When rendering a large number of elements , But the data is immutable , skip Proxy The conversion of can bring performance improvement .

let result = { description: { version: '2.0' } };
const resultProxy = reactive(result);
console.log(isReactive(resultProxy.description)); // true
 Copy code 

3.1.2 ref

Takes a parameter value and returns a responsive and changeable ref object .ref Object has a single property that points to an internal value , If you pass in ref It's an object , Will call reactive Method for deep response conversion .

3.1.3 toRef

It can be used to create a property Sex creates a  ref. Then you can put ref Pass out , So as to maintain a good understanding of its source property Responsive connection for .

3.1.4 toRefs

Convert a responsive object to a normal object , Where each property They all point to the original object property Of ref.

Solve the problem of missing response characteristics of deconstruction assignment : Response to data loss , You will find that the data has changed , The view has not changed .

// Combinatorial function :
function useMousePosition() {
const pos = reactive({
x: 0,
y: 0,
})
return pos;
}
// Consumer components 
export default {
setup() {
// Here deconstruction assignment will lose responsiveness ! 
const { x, y } = useMousePosition()
return {
x,
y,
}
// Writing this will also lose responsiveness !
return {
...useMousePosition(),
}
// Write it like this , Remain responsive !
// You have to go back to `pos` In itself , And press `pos.x` and `pos.y` Reference... In the template x and y.
return {
pos: useMousePosition(),
}
},
}
// Or in a combinatorial function 
function useMousePositionRef() {
const pos = reactive({
x: 0,
y: 0,
})
// Use toRefs 
return {...toRefs(pos)};
}
 Copy code 

3.2 vue3.0 Dependent collection implementation

Vue.js 2.0 First, all the data used will be called , This triggers all getter function , And then pass Dep Object to collect all responsive dependencies , Call all Watcher perform Render operation , There will be virtual Dom Storage and comparison of , Then render the page . When there is data change, it will trigger setter function , Trigger dep.notify(), And then call Watcher Of update, push Vue In the asynchronous observation queue , And finally render to the page .

Here is a picture Vue.js 2.0 Rely on collecting brain maps

image.png

Vue.js 3.0 adopt reactive modular Turn data into proxiable objects , And then through Proxy Acting as agent ,handle Intercept all kinds of get,set operation , When get In operation , Would call effect Module track Method for dependency collection , When set when , Will pass effect in trigger Trigger .

Here is a picture Vue.js 3.0 Rely on collecting brain maps image.png

3.2.1 Object.defineProperty contrast Proxy

Object.defineProperty
  • Only the properties of the object can be hijacked ;
  • Modify the original value ;
Proxy
  • Proxies are objects , There is no need to recursively traverse properties , Performance improvement , Use Reflect Solve deep nesting ;
  • be relative to defineProperty,Proxy No doubt more powerful , Can proxy array , object 、 Method 、 And it provides 13 Method of intercepting attribute access in operation traps(get,set,has,deleteProperty wait );
  • Proxy raw data , Does not change the value of the original data ;

3.3 Cross component data sharing

There are usually some deeply nested components in our projects , Deep child components only need part of the parent component . under these circumstances , If still will prop Pass down the component chain step by step , It could be a lot of trouble . In this case , We can use vuex, Or a couple  provide  and  inject Realize cross component data sharing .

No matter how deep the component hierarchy is , A parent component can be a dependency provider for all its child components . This feature has two parts : The parent component has one  provide  Options to provide data , The subcomponent has a  inject  Option to start using this data .

image.png

4.3.1 Project application

We use it in the outermost root component provide, All its internal descendant components can use inject Data acceptance , If its data is changed , All places where this variable is used watch、watchEffect、computed Will be re implemented , And re render the dependent variables dom, This enables cross component data changes , And the view is updated .

globalProvide.tsx

import { defineComponent, provide, reactive, Fragment } from 'vue';
export default defineComponent({
name: 'globalProvide',
setup(props, { slots }) {
// Global configuration responsive data
const globalData = reactive({
// This is just an example , The global data structure needs to be designed by yourself
ctx: {
currentPage: 0,
},
});
provide('globalData', globalData);
return () => {
return <Fragment>{slots.default?.()}</Fragment>;
};
},
});
 Copy code 

center.vue

The outermost component uses the component encapsulated above , All internal deep-seated components can be used provide Defined global data .

<template>
<globalProvide>
<leftComponent/>
<rightComponent/>
</globalProvide>
</template>
 Copy code 

leftComponent.tsx

Internal alignment of components globalData The data has been changed , All other deep-seated components , Yes globalData.ctx.currentPage Places to rely on , Will automatically update related dependencies and views .

import { defineComponent, inject, onMounted } from 'vue';
export default defineComponent({
name: 'leftComponent',
setup() {
const globalData = inject('globalData');
onMounted(() => {
globalData.ctx.currentPage = 2;
})
return () => {
return (
<div>{globalData.ctx.currentPage}</div>
)
}
}
})
 Copy code 

We can see ant-design-vue in ConfigProvider  Global configuration That's how it works .

image.png

5、 ... and 、 Sound wave lion roar

The supreme internal skill of Shaolin school , A break of drinking contains deep internal power , It has a great effect on the enemy and police friends .

You can use the sound wave lion roar in Wulin to make your opponent feel the transmission of sound , And in the vue3.0 How to realize cross component communication between components in ? Look at our example below .

5.1 emits Introduce

emits Can be an array or an object , Trigger custom events from components ,emits Can be a simple array , It could be an object , The latter allows you to configure event validation .

5.1.1 emits verification

Examples of subcomponents :

import { defineComponent } from 'vue';
export default defineComponent({
name: 'demoEmits',
// It can be done to emits Check the message 
emits: {
clickItem: ({type}) => {
// type == ok, Check by 
if (type == 'ok') {
return true;
}
// Otherwise prompt 
console.warn(' Verification failed ');
}
},
setup(props, {slots, emit}) {
const clickHandle = (event) => {
emit('clickItem', {type: 'ok'});
}
const demoProps = {
style: {},
class: [],
onClick: clickHandle,
}
return () => {
<div {...demoProps}> Send a message </div>
}
}
})
 Copy code 

5.2 Parent child communication :

In the use of vue2.0 version , Using parent-child communication is more common , There is no particularly detailed introduction here , Refer to the example above for sub components .

Example of parent component :

<demo-emits @clickItem="() => console.log('demoFn')"/>
 Copy code 

5.2.2 Cross component communication

In actual development , In a scenario where deep-seated components communicate with other components , Communication across components is particularly important . vue3.0 It is not supported vue2.0 event-bus The pattern implements cross component message communication . Here is an official third-party library recommendation mitt or tiny-emitter, The example here uses mitt.

Mount the method of the third-party library in provide Defined in the global shared data eventBus In the namespace .

In this way, deeply nested components can pass through globalData.eventBus.emit Method to send a message ,globalData.eventBus.on Message listening , Same as eventBus Same use .

import { defineComponent, provide, reactive, Fragment } from 'vue';
import mitt from 'mitt';
export default defineComponent({
name: 'globalProvide',
setup(props, { slots }) {
const emitter = mitt();
const globalData = reactive({
ctx: {
currentPage: 0,
},
eventBus: emitter, // Mounted on eventBus Namespace
});
provide('globalData', globalData);
return () => {
return <Fragment>{slots.default?.()}</Fragment>;
};
},
});
 Copy code 

Other alternatives can refer to event-bus.

6、 ... and 、 Key summary

  1. h Rendering functions can be used flexibly , And it can be styled 、style、 Custom properties 、 Instructions 、 Binding of events 、 Slot rendering , You can also use JSX grammar , Make the code more readable .
  2. vue2.0 and vue3.0 Differences between data broker implementation schemes .
  3. have access to provide Realize the data sharing of deep-seated components 、 Cross component message communication mechanism ( Three party Library mitt).

processon Invite Links

Reference material :

  1. vue3js.cn/docs/api/op…
  2. v3.cn.vuejs.org/guide/migra…
  3. 2x.antdv.com/components/…
  4. github.com/vuejs/jsx-n…
  5. github.com/vuejs/rfcs/…
版权声明
本文为[Please call me ames]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909131415439h.html

  1. 350 questions d'entrevue Android partage, technologie d'architecture de cache
  2. The space is not vulgar, the configuration is rich, the leather is durable, less worry, and the high configuration is less than 100000!
  3. Vous permet de passer rapidement à travers l'entrevue de saut d'octets et d'aller de l'avant
  4. Résumé des questions d'entrevue technique d'Alibaba Baidu et d'autres grandes usines à la fin de l'année, et analyse de la dernière vraie question d'entrevue Android en 2021
  5. Avec cet ensemble de questions d'entrevue Java, l'ensemble de questions de base d'entrevue de bat,
  6. Avec cet ensemble de questions d'entrevue Java, les notes avancées Java de niveau divin sont systématisées,
  7. Opérateurs arithmétiques et opérateurs de comparaison pour JavaScript, Introduction classique au développement web
  8. Explorer le cadre open source Android - 1. Okhttp Source Analysis
  9. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  10. Partager l'expérience de l'examen et du développement de l'arrière - plan, en s'appuyant sur les questions d'entrevue et les réponses,
  11. Site Web pour partager vos expériences d'entrevue, Tencent Bull vous apprend à écrire votre propre cadre Java!
  12. Notes d'étape Android structurées, sélection de vrais problèmes d'entrevue Android
  13. Dictionnaire distribué: communication de cache limitée par le courant, sujets d'entrevue pour certaines questions courantes dans le développement Java,
  14. Tianci girlfriend Tangyuan attended the event for the second time. Her appearance was comparable to that of a star. The audience shouted that Tianci was blessed!
  15. Introduction au JavaScript chapitre 15 (objets, clairvoyance)
  16. La dernière revue scientifique de l'académicien Luo Liqun: architecture de la boucle neuronale pour stimuler la nouvelle Ia
  17. Basic knowledge of components in Vue "I"
  18. J'a i appris quelques petites choses sur l'entrevue et j'ai acheté un tutoriel en 19998.
  19. Dix minutes pour vous faire passer en revue les points de connaissance que Spring demande souvent, le chemin du retour Jedi d'un programmeur âgé de 35 ans,
  20. Want to know the implementation and application of single instance mode in the front end?
  21. Progressive react source code analysis - Implementation of ref API
  22. Webpack5 learning -- code compression
  23. Front and back end data interaction (V) -- what is Axios?
  24. Knowledge points related to react routing
  25. On demand introduction of react antd + customized theme
  26. GPG management submission signature verification
  27. [babylonjs] babylonjs practice (XII) -- drawing lane lines
  28. After brushing the 12 sliding windows, you can tear the front end by hand
  29. Vue fruit bookkeeping - money.vue component
  30. Propriétés et méthodes des objets Array en javascript!,Pseudo - classes et pseudo - éléments pour CSS
  31. JS contains the function code
  32. Typescript record (I)
  33. Take you to learn more about nginx basic login authentication: generating passwords using OpenSSL
  34. Is componentization obsolete? Introduction to micro front end architecture
  35. Leetcode day 18
  36. Simple code to achieve a, 1W + people see the Mid Autumn Festival blessing
  37. Design pattern -- agent pattern
  38. Vs Code theme recommendation in 2021
  39. Mon expérience réelle dans l'externalisation Android à Huawei, préparation de l'entrevue de développement Android
  40. J'ai les questions et les réponses d'entrevue de développement d'octets de rêve et Tencent double offer, Android
  41. Fatal Magic: countless sacrifices under gorgeous magic
  42. Mon expérience d'entrevue principale est partagée avec l'expérience d'apprentissage
  43. Mon expérience d'entrevue Android de Tencent partage, plugin Android
  44. Partage de questions d'entrevue Java à double saut d'octets non - premier cycle, un article vous apprend à gérer l'entrevue réseau informatique,
  45. Questions d'entrevue CSS (notes)
  46. Syntaxe de base de la classe
  47. Héritage de classe
  48. Mise en œuvre simple de 30 minutes pour un filtrage rapide des chaînes de tableau 10W +.
  49. Vue 3 tri des documents démarrage rapide
  50. Collection de code de base JavaScript (1)
  51. National secret nginx Container actual Fighting
  52. Quelques lignes de css pour rendre votre page tridimensionnelle
  53. C'est super détaillé, de "finir" ce 300 pages de 1000 questions d'entrevue,
  54. Take you in-depth understanding of nginx basic login authentication (including all configuration steps and in-depth analysis)
  55. Après avoir mangé, assurez - vous d'augmenter votre salaire de 5K et de rester debout tard pour trier les questions d'entrevue Java de millet.
  56. Résumé des questions d'entrevue pour les entreprises Internet nationales de première ligne, qui doivent être posées lors de l'entrevue d'emploi Java de la grande usine en 2021,
  57. "L'amour à première vue", la nouvelle BMW 2 coupe réelle, vous êtes surpris?
  58. Questions d'entrevue de test avancé de Dachang, liste des compétences de base de l'entrevue Java,
  59. Tableau 2D trié par un champ
  60. JS est souvent utilisé pour déterminer si l'objet est vide