This is the 23rd day of my participation in the August More Text Challenge.More challenges in August

In this article, we look at the use of Computed and Watch and some of the new responsive apis in Vue3.2, and what we need to be aware of.

How to use

computed

In Vue2, it is a calculated attribute, and in Vue3, it is a calculated method. In fact, they do the same thing, but the usage is a little different. In this case, computed uses are as follows:

shorthand

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

Takes a getter function and returns an immutable reactive ref object for the value returned from the getter. When count changes, plusOne increments by one.

All written

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

It can also use objects with get and set functions to create writable ref objects. When count changes, plusOne increments by one; When plusOne changes, count decreases by one.

It’s worth noting that in our actual development, if we just used count, we would have been able to abbreviate it; If we need to change the value of plusOne, we can only use full write mode.

watchEffect

To automatically apply and reapply side effects based on reactive state, we can use the watchEffect method. It executes a function passed in immediately, tracing its dependencies responsively, and rerunking the function when its dependencies change. Use as follows:

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

Each time the value of count changes, the side effect function is triggered, which prints: output log:? . So how do you stop listening for this side effect? While watchEffect stops automatically when a component is uninstalled, it can also be stopped manually, as follows:

stop()
Copy the code

Now that we can stop listening for side effects, we should be able to get rid of them. Officially, a function that listens for incoming side effects can receive an onInvalidate function as an input parameter to register a callback in the event of a cleanup failure. How do we use it? Suppose we have a requirement:

An API for retrieving data, passing the parameter id, will make a request every time the id changes, so what if we only want to retrieve the data once?

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

WatchPostEffect and watchSyncEffect

These two apis are new methods in Vue3.2, which is equivalent to adding a parameter to watchEffect. Currently, they are not used much, and will be updated later.

watch

The Watch API is the same as the optional API this.$watch, which listens for a specific data source and performs side effects in a separate callback function. It is also lazy by default, and compared to watchEffect, Watch allows us to:

  • Lazy execution of side effects;
  • Be more specific about the state in which the listener should be triggered to restart;
  • Accesses the previous and current values of the monitored state.

The usage method is as follows:

Listen on a single source

// Listen for a getter
const state = reactive({ count: 0 })
watch(
  () = > state.count,
  (count, prevCount) = > {"dosomething"})// Listen directly on a ref
const count = ref(0)
watch(count, (count, prevCount) = > {"dosomething"})
Copy the code

Listening for multiple sources

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

When listening for more than one listener, it takes an array as an argument. In addition, we need to pay attention to:

Watch and watchEffect have the same behavior with respect to manual stopping, invalid side effects (passing onInvalidate as the third argument to the callback), Flush Timing, and debugging.

effectScope

Effect Scope is a high-level API primarily used by library authors. Create an effect scope object that captures the reactive effects (such as calculations and observers) created in it so that these effects can be put 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 the code

We can use effectScope to batch some operations.

getCurrentScope

Gets the current scope content, which is the effectScope above, as follows:

function getCurrentScope() :EffectScope | undefined
Copy the code

onScopeDispose

Registers a callback function in the current scope that will be called when the effectScope stops. The function looks like this:

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

conclusion

  1. For computed, we generally use shorthand in projects to meet our needs, and it is not necessary to write in full.

  2. WatchEffect and Watch should be used reasonably according to requirements.

  3. The new apis, which we don’t normally use, can be used when you need to project on some behavior.

For more articles, the portal has opened: Look back at the Vue3 catalogue!