2

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

This is the second part of "Writing Better Code with Composition", the previous article:

What if your composition could change what it returns based on its usage? If we only need one value, it can do so. If you need to return the whole object, it can do that too.

This article will introduce a pattern for adding dynamic returns to composable objects. We'll see when to use the pattern, how to implement it, and see some examples of patterns in use.

Patterns for dynamic return values

This pattern continues the "why not the best of both worlds?" ideas from the previous article on flexible parameters. A composable can return either a single value or an object of values.

 // 返回一个值
const isDark = useDark();

// 返回多个值
const {
  counter,
  pause,
  resume,
} = useInterval(1000, { controls: true });

This is a nice feature because we can control the level of complexity. Simple when it is needed. When complexity is required, it is complexity.

VueUse's useInterval composition uses this pattern.

Most of the time, when using useInterval , we only need counter . So by default it just returns this.

 // 默认行为
const counter = useInterval(1000);

// 1...
// 2...
// 3...

If you want to suspend and reset counter , you can also do that with the controls parameter.

 const {
  counter,
  pause,
  resume,
} = useInterval(1000, { controls: true });

// 1...
// 2...
pause();
// ...
resume();
// 3...
// 4...

Next, let's take a look at how this pattern is implemented.

accomplish

To implement this pattern, we need to do two things:

  • Add an option to the options object to turn it on
  • Use this option to change the behavior of retrun

The following is an approximate implementation idea:

 export default useComposable(input, options) {
  // 1. Add in the `controls` option
  const { controls = false } = options;
  
  // ...

  // 2. Either return a single value or an object
  if (controls) {
    return { singleValue, anotherValue, andAnother };
  } else {
    return singleValue;
  }
}

Maybe you want to toggle on an existing option instead of just using a controls option for this purpose. Maybe use a ternary expression or a more concise than if statement. There may also be a completely different way that works best for you. The important thing about this mode is the switching, not the way it is switched.

Next, let's see how some composition methods of VueUse implement this pattern.

useInterval

First, let's take a deep dive into how useInterval works.

At the top level of the composable, we deconstruct the options object and take out controls 选项并将其重命名为exposeControls , the default value is false.

 const {
  controls: exposeControls = false,
  immediate = true,
} = options;

Finally, in the if statement, judge exposeControls , if true, just return counter and other attributes, otherwise only return counter .

 if (exposeControls) {
  return {
    counter,
    ...controls,
  };
else {
  return counter;
}

With these two pieces of code, we can make any composable have a more flexible return statement.

Now, let's take a look at the useNow function.

The useNow composition returns a Date object for the current time and updates the loudness.

 const now = useNow();

By default, it updates itself every frame - 60 times per second by default. We can change its update frequency, as well as pause and resume the update process.

 const { now, pause, resume } = useNow({ controls: true });

This combination works very similarly to the useInterval combination. Internally, they both use the useIntervalFn helper exposed by VueUse.

First, we destructure the options object, get the controls option, and rename it to exposeControls again to avoid naming conflicts.

Then we return at the end of the composable. Here we use the if statement to switch between the two cases.

 if (exposeControls) {
  return {
    now,
    ...controls,
  };
else {
  return now;
}

As you can see, the implementation of this pattern is almost identical in useInterval and useNow combinations. All compositions in VueUse that implement this pattern are implemented in this particular way.

Below is a composable list of all the implementations of this pattern in VueUse that I could find for you to explore further yourself.

  • useInterval
  • useTimeout
  • useNow
  • useTimestamp
  • useTimeAgo

Summarize

We saw that dynamic return values give us more flexibility in choosing how to use composables. We can get a single value if that's what we need. We can also get an entire object containing values, methods and other things we might want.

But we didn't just look at the pattern itself. We saw how VueUse's useInterval and useNow components implement this pattern.

This pattern is great for simplifying our code in most cases, while still allowing for greater complexity when needed. It's kind of like a desk with drawers. You can put a lot of stuff on the table when you need it. But you can also keep them in a drawer to keep things tidy.


The bugs that may exist in editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, here is a useful BUG monitoring tool , Fundebug .

Author: Michael Thiessen Translator: Xiaozhi Source: vuemastery

Original: https://www.vuemastery.com/blog/coding-btter-composables-1-of-5

comminicate

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.


王大冶
68.1k 声望105k 粉丝