Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

You might know ref, but you might not know how to customize a ref, right

Let’s take a look

As we know, the REF function can create a reactive data that updates the UI as the data is updated

Sometimes we want to be able to display the control dependency trace and trigger the response, so we can use the customRef function to customize a ref

Return customRef()

Note:

The customRef function takes a factory function with two arguments, track for tracing and trigger for triggering the response, and returns an object with get and set methods

Official example: Implementing v-Model with stabilization using custom ref:

<input v-model="text" />
Copy the code
function useDebouncedRef(value, delay = 200) {
  let timeout
  return customRef((track, trigger) = > {
    return {
      get() {
        track()
        return value
      },
      set(newValue) {
        clearTimeout(timeout)
        timeout = setTimeout(() = > {
          value = newValue
          trigger()
        }, delay)
      },
    }
  })
}

export default {
  setup() {
    return {
      text: useDebouncedRef('hello'),}}}Copy the code

In the code above, displaying track() in get means that the data needs to be tracked, and calling trigger() in set means that the UI needs to be updated when the data is modified.

To customize a ref function using the customRef function:

1. The function returns customRef()

2. CustomRef accepts two parameters track and trigger

3. CustomRef returns an object

4. The object returned by customRef must implement the set and GET methods

5. The call track() displayed in GET means that the data needs to be tracked, and the call trigger() displayed in set means that the UI needs to be updated when the data is modified

That’s all for this article