Vue3 intermediate guide - composition API

vue3 vue intermediate guide composition


Compostition API aggregate , solve Vue2 Component development issues

better TypeScript Support

new Api Support

What is? reactive?

  • reactive yes vue3 Methods for implementing responsive data provided in
  • stay vue2 In this paper, the response data is obtained through defineProperty To achieve
    • Because it's flawed , In dealing with arrays , therefore vue3 In this paper, the response data is obtained through ES6 Of Proxy To achieve

reactive Be careful

  • reactive Argument must be an object (json/arr)
  • If reactive Passing other objects
    • Modify objects by default , The interface doesn't update automatically .
    • If you want to update , It can be done by reassigning .

What is? ref?

  • ref and reactive equally , It's also used to implement responsive data
  • because reactive You have to pass an object , All this leads to a lot of trouble in enterprise development if we only want to make a variable responsive , all vue3 It gives us ref Method , To monitor the simple

ref The essence

  • ref The essence of the bottom is reactive, The system will automatically give ref The value passed in converts it to something like this

    ref(xxx) => reactive({value:xxx})
     Copy code 

ref Be careful

  • stay vue Use in ref Declared variables do not need to pass through in the template .value obtain , Because in template In template ,vue Will automatically add to us .value
  • stay js Use in ref Or change ref The value of must pass .value Get and change

Recursive listening

  • By default , Whether through ref still reactive It's all recursive listening

  • Problems with recursive listening , If the amount of data is large , Very performance intensive

  • Non recursive listening

shallowReactive

 let state = shallowReactive({
a: "a",
b: {
c: "c",
d: {
e: "e"
}
}
})
 Copy code 

Be careful :shallowReactive Properties for creating non recursive listening , Only the first layer will be monitored

shallowRef

 let state = shallowRef({
a: "a",
b: {
c: "c",
d: {
e: "e"
}
}
})
 Copy code 

Be careful :shallowRef The monitor is .value The change of . Not at all shallowReactive Changes in the first layer .

triggerRef

 let state = shallowRef({
a: "a",
b: {
c: "c",
d: {
e: "e"
}
}
})
// The modified page does not update the view 
state.b.d.e = "ee"
// Actively trigger view updates 
triggerRef(state)
 Copy code 
  • Application scenarios

    Half the time we use ref and reactive that will do , Only when the amount of data to be monitored is large , We use shallowRef/shallowReactive

toRaw

understand toRaw Before we can look at the following list to understand why we need to use toRaw

<script lang="ts">
import { reactive } from "vue";
export default {
name: "App",
setup() {
let data = {
name: " Only tomato and scrambled eggs ",
age: 18,
};
let state = reactive(data);
function changeAge() {
// state.age += 1;
data.age += 1;
console.log(data);
console.log(state);
}
return {
state,
changeAge,
};
},
};
</script>
 Copy code 

We will find that , The data has changed, but the view has not been updated . One thing we understand here is data and state It's a citation relationship .state The essence of Proxy object , In this Proxy Object data

If you modify it directly data, The data is changing , But it can't trigger page updates

Only the wrapped object can be modified , Will trigger page updates

What does this method do? The scene is , When we just want to modify the data , But I don't want to use it when the view changes . because ref and reactive The characteristic of data type is that every time the data is modified, it will be tracked , Will update ui Interface . Very performance intensive . If we have some operations that don't need to track and update the page , Then you can go through toRaw How to get his raw data . This saves performance

summary :toRaw Method to get raw data from responsive data

Be careful : When we go through toRaw obtain ref Type of raw data, you will find that you can't get .

ref The essence :reactive

Ref(obj) => reactive({value: obj})

That's why we need to go through .value To get ref Data created

summary : If you want to pass toRaw Get ref Type of raw data ( The data passed in at the time of creation ) It took so long to tell toRaw Method , When you want to get .value Value . Because after Vue After processing ,.value It's the original data that's stored in .

<script lang="ts">
import { ref, toRaw } from "vue";
export default {
name: "App",
setup() {
let data = {
name: " Only tomato and scrambled eggs ",
age: 18,
};
let state = ref(data);
let data2 = toRaw(state.value);
console.log(data2);
function changeAge() {
// state.age += 1;
data.age += 1;
console.log(data);
console.log(state);
}
return {
state,
changeAge,
};
},
};
</script>
 Copy code 

Markrow

Data that will never be tracked , By markrow Declared variables are never tracked , Even if reactive perhaps ref Statement . Modifying the data doesn't change the data , It doesn't trigger view updates

ref and toRef The difference between

  • ref and toRef Modifying responsive data will affect previous data
  • ref Data changes , The interface will automatically update
  • toRef Data changes , And the interface doesn't update automatically

toRef Application scenarios : If you want to associate responsive data with previous data , And I don't want to update after updating the responsive data UI, Then you can use it .

toRefs

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

In other words, all the attributes of an object can be changed into responsive data . All of these methods are designed to improve performance . The main use is ref and reactive

customRef

Create a custom ref, And explicitly control its dependency tracking and update trigger . It needs a factory function , This function receives track and trigger Function as parameter , And it should return a message with get and set The object of .

Why customize ref Let's talk about it later . Let's talk about how to achieve

<script lang="ts">
import { customRef } from "vue";
function myRef(value) {
return customRef((track, trigger) => {
return {
get() {
// track() The method tells vue This data is to be tracked 
track();
console.log("get", value);
return value;
},
set(newValue) {
value = newValue;
console.log("set", value);
// trigger() The method tells vue Update the view 
trigger();
},
};
});
}
export default {
name: "App",
setup() {
let state = myRef(18);
function change() {
state.value = 20;
}
return {
state,
change,
};
},
};
</script>
 Copy code 

Why customize ref

The first thing we need to know is setup A function can only be a synchronous function , It can't be an asynchronous function . As for why it can't be an asynchronous function, we are setup prefix async Let the post normal declaration variable display in the page to know the reason .

So when we need to initiate in the business ajax Request for data , And want to pass async await To get the data doesn't work .

Then it can't be used async await It means that there may be a lot of callback functions in our code .

So we also want to write in the same way that we used to synchronize code You can consider using custom ref.

<script lang="ts">
import { customRef } from "vue";
function myRef(value) {
return customRef((track, trigger) => {
fetch(value)
.then(async (res) => {
value = await res.json();
console.log(value);
trigger();
})
.catch((reason) => {
console.log(reason);
});
return {
get() {
// track() The method tells vue This data is to be tracked 
track();
console.log("get", value);
return value;
},
set(newValue) {
value = newValue;
console.log("set", value);
// trigger() The method tells vue Update the view 
trigger();
},
};
});
}
export default {
name: "App",
setup() {
let state = myRef("../public/data.json");
function change() {
state.value = 20;
}
return {
state,
change,
};
},
};
</script>
 Copy code 

ref Get elements

vue3 and vue2 Different , vue3 did not this.$ The attributes of those things . It's also easy to get elements

<template>
<div>
<div ref="box"> I am a box</div>
</div>
</template>
<script lang="ts">
import { onMounted, ref } from "vue";
export default {
name: "App",
setup() {
let box = ref(null);
onMounted(() => {
console.log(box.value);
});
return {
box,
};
},
};
</script>
 Copy code 

Notice here why the print is box.value And above ref The reason for getting the declared variable is the same .

Why is it onMounted Print in . This life cycle and 2 It's consistent . because setup and created also beforeC reated equally , During this period dom Not yet created

readonly family

  • readonly

Accept an object ( Responsive or pure object ) or ref And returns the read-only proxy of the original object . Read only agents are deep : Any nested accessed property It's also read-only .

Used to create a read-only property , And it's recursively read-only

  • shallowReadonly

Used to create a read-only data , But not recursively read-only . Only the first layer is read-only

  • isReadonly

Used to determine whether an attribute is a readonly Returns a Boolean value

You may have questions here, so I'll use it directly const Just declare variables . Pay attention here .const Commonly used to declare constants , And usually declare the original type . But if you declare a reference type . Any variable cannot be reassigned . But the value of a property of a reference type can be changed .

An understanding of the nature of responsive data

  • stay vue2.x China is through defineProperty To implement responsive data . But there are some flaws , For example, array processing

  • stay vue3.x China is through Proxy To implement responsive data

// Simple implementation 
let obj = { name: " tomato ", age: 18 }
let state = new Proxy(obj, {
get(obj, key) {
console.log(obj, key); // {name: ' tomato ', age: 18} name
},
set(obj, key, value) {
console.log(obj, key, value); // {name: ' tomato ', age: 18} name Scrambled eggs 
obj[key] = value
console.log(" to update UI View ");
return true
}
})
console.log(state.name); // tomato 
state.name = " Scrambled eggs "
console.log(state); // Proxy {name: ' Scrambled eggs ', age: 18}
 Copy code 

Through the above simple Liezi . We can do a lot of things in getting and setting values .

Be careful :set Method must tell the return value that the operation is successful . Because in set There may be more than one modification in the operation, such as array

proxy Proxy array

// Simple implementation 
let arr = [1, 2, 3]
let state = new Proxy(arr, {
get(obj, key) {
console.log(obj, key); // [1, 2, 3] 1
return obj[key]
},
set(obj, key, value) {
/**
* [ 1, 2, 3 ] push
[ 1, 2, 3 ] length
[ 1, 2, 3 ] 3 4
to update UI View
[ 1, 2, 3, 4 ] length 4
to update UI View
[ 1, 2, 3, 4 ]
*/
console.log(obj, key, value);
obj[key] = value
console.log(" to update UI View ");
return true
}
})
// console.log(state[1]) // 2
state.push(4)
console.log(state);
 Copy code 

Through the above code, we will find that set Method is executed twice . Once it was [ 1, 2, 3 ] 3 4, Once it was [ 1, 2, 3, 4 ] length 4

set Method must tell whether the current operation is successful through the return value . If I take the top return ture If you look down, you will report an error

state.push(4)
^
TypeError: 'set' on proxy: trap returned falsish for property '3'
at Proxy.push (<anonymous>)
at Object.<anonymous> (/Users/cctvabu/vite-vue3-project/proxy.js:26:7)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
 Copy code 

So pay attention to set Method must tell whether the current operation is successful through the return value


That's what I learned api knowledge . The follow-up is still under study and supplement . Of course, there are some mistakes, please point out , I look up the information and revise it .

job-hunting

I am going to change my job recently . You can contact me if you have a job introduction ~

版权声明
本文为[I only know how to scramble eggs with tomatoes]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503191542450K.html

  1. CSS layout
  2. Application scenario explanation of Vue dynamic component
  3. Redux learning notes 04 -- using multiple reducers to manage data
  4. After three months of typescript writing, what have I learned?
  5. Node family - what is a callback?
  6. React -- a simple implementation of render & create element
  7. JS learning simple usage of jquery
  8. Seamless love
  9. 小白前端入门笔记(12),设置哑链接
  10. Small white front-end entry notes (12), set dumb links
  11. Vue2. X opens composition API and TSX
  12. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  13. Flex learning notes
  14. The most essential closure article in the eastern hemisphere
  15. 2021-05-03 hot news
  16. Sword finger offer -- reverse order pair in array (JS Implementation)
  17. Working process of scaffold
  18. Use decorator mode to strengthen your fetch
  19. [JS] scope (Introduction)
  20. Employment information statistics network (interface document)
  21. Analysis of MVC
  22. [middle stage] please stay and join me in the backstage
  23. Understanding front end garbage collection
  24. [continuous update] front end special style implementation
  25. Flutter product analysis and package reduction scheme
  26. XPath positioning
  27. 前端开发css中的flex布局的使用
  28. The use of flex layout in front end development CSS
  29. JQuery核心函数和静态方法
  30. JQuery core functions and static methods
  31. Node family - understanding of blocking and non blocking
  32. 热点微前端Microfrontend的讨论:谷歌AdWords是真实的微前端
  33. Vue source code analysis (2) initproxy initialization proxy
  34. What's TM called react diff
  35. Summary of common front end data structure
  36. Useeffect in hooks
  37. [encapsulation 02 design pattern] Command pattern, share meta pattern, combination pattern, proxy pattern, strategy pattern
  38. Front end notes: virtual Dom and diff of vue2. X
  39. The best code scanning plug-in of flutter
  40. The simplest plug-in for rights management of flutter
  41. 21. Object oriented foundation "problems and solutions of object traversal"
  42. Discussion on hot micro front end: Google AdWords is a real micro front end
  43. Usecallback and usememo for real performance optimization
  44. 【前端圭臬】十一:从规范看 JavaScript 执行上下文(下)
  45. [front end standard] 11: Javascript execution context from the perspective of specification (2)
  46. Hexagonal六角形架构ReactJS的实现方式 - Janos Pasztor
  47. Transaction of spring's reactive / imperative relational database
  48. The implementation of hexagonal hexagonal reactjs Janos pasztor
  49. HTTP状态码:402 Payment Required需要付款 - mozilla
  50. HTTP status code: 402 payment required - Mozilla
  51. Factory mode, constructor mode and prototype mode
  52. Build the scaffold of react project from scratch (Series 1: encapsulating a request method with cache function based on Axios)
  53. Cocos Quick Start Guide
  54. Comparison of three default configurations of webpack5 modes
  55. A case study of the combination of flutter WebView and Vue
  56. CSS: BFC and IFC
  57. A common error report and solution in Vue combat
  58. JS: this point
  59. JS: prototype chain
  60. JavaScript series -- promise, generator, async and await