current position:Home>Looking back on the API of vue3 (10)

Looking back on the API of vue3 (10)

2021-08-27 10:06:59 Also laugh

This is my participation 8 The fourth of the yuegengwen challenge 23 God , Check out the activity details :8 Yuegengwen challenge

Let's talk about this article Computed And watch as well as Vue3.2 Some new responsiveness API Use , And what we need to pay attention to .

How to use

computed

stay Vue2 In is the calculated property , stay Vue3 The calculation method is , In fact, their functions are the same , But there are some differences in usage , here computed Can be used as follows :

Abbreviation

const count = ref(1)
const plusOne = computed(() => count.value + 1)
 Copy code 

Accept one getter function , And from getter The returned value returns an invariant response  ref  object . here ,count When things change ,plusOne One will be added .

Full write

const count = ref(1)
const plusOne = computed({
  get: () => count.value + 1,
  set: val => {
    count.value = val - 1
  }
})
 Copy code 

It can also be used with  get  and  set  Function to create a writable ref object . here ,count When things change ,plusOne Will add one ;plusOne When things change ,count It will be reduced by one .

It's worth noting that : In our actual development , If it's just a simple use count, Then our abbreviations are enough ; If you need to change plusOne Do the operation when the value of , Then we can only use full write mode .

watchEffect

In order to respond to the State Auto apply and Reapply side effect , We can use  watchEffect  Method . It immediately executes an incoming function , At the same time, it is responsive to trace its dependencies , And rerun the function when its dependency changes . Use as follows :

const count = ref(1)
const stop = watchEffect(() => console.log(`output log:${count.value}`))
 Copy code 

When count When the value of is changed , Will trigger this side effect function , That is, it will print out :output log:?. So how to stop listening for this side effect ? Although when the component is unloaded  watchEffect Will automatically stop , But we can also stop it manually , as follows :

stop()
 Copy code 

Now that we can all stop listening for side effects , Then we should be able to eliminate the side effects . The official said , The function passed in by listening for side effects can receive a  onInvalidate  Function as input parameter , Used to register the callback when the cleanup fails . What if we use it , Suppose we have such a need :

A way to get data api, Biography is id, Every time id When it changes , We all have a request , So what if we just want to get it once , Here we can eliminate the side effects , as follows :

watchEffect(onInvalidate => {
  const token = getData(id)
  onInvalidate(() => {
    token.cancel()
  })
})
 Copy code 

watchPostEffect and watchSyncEffect

these two items. api yes Vue3.2 New method , It is equivalent to giving watchEffect Added a parameter , Not much is used at present , It will be updated later .

watch

watch API And option API this.$watch It's the same thing ,watch  You need to listen on specific data sources , And perform side effects in a separate callback function . By default , It's also inert , And watchEffect Compare ,watch  Allow us :

  • Inert execution of side effects ;
  • More specifically, state that the listener should be triggered to run again ;
  • Access the previous and current values of the listening state .

How to use it is as follows :

Listen to a single source

//  Listen for one  getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {"dosomething"}
)

//  Listen directly to a  ref
const count = ref(0)
watch(count, (count, prevCount) => {"dosomething"})
 Copy code 

Listen to multiple sources

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  "dosomething"
})
 Copy code 

When listening to multiple , Will take the form of an array as an argument . In addition, we need to pay attention to :

watch And watchEffect stay Manual stop , Side effects are invalid  ( take  onInvalidate  Passed to the callback as the third parameter ),flush timing  and  debugging  Have the same behavior .

effectScope

Effect scope It's a kind of advanced API, Mainly for library authors . Create an effect range object , This object can capture the reactive effects created in it ( For example, calculation and observer ), So that you can put these effects together , as follows :

const scope = effectScope()

scope.run(() => {
  const doubled = computed(() => counter.value * 2)
  watch(doubled, () => console.log(doubled.value))
  watchEffect(() => console.log('Count: ', doubled.value))
})
//  Stop all effects in this scope 
scope.stop()
 Copy code 

We can use effectScope To batch process some operations .

getCurrentScope

Get the content of the current scope , That is to say effectScope, Its function is as follows :

function getCurrentScope(): EffectScope | undefined  Copy code 

onScopeDispose

Register a callback function on the current scope , This callback function will effectScope Call... When it stops , Its function is as follows :

function onScopeDispose(fn: () => void): void  Copy code 

summary

  1. about computed, In the project, we usually use abbreviations to meet our needs , It's not necessary to write it all .

  2. watchEffect And watch We should use them reasonably according to our needs .

  3. Newly added API, In general, we may not use , But when you need to do project operations on some behaviors , They can be used .

copyright notice
author[Also laugh],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827100654539v.html

Random recommended