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:
The text begins.
When using vue composition, sometimes I want to use ref, and sometimes I don't want to use it. In this section, I introduce a pattern that allows me to use refs or not to make components more flexible.
Use ref and unref for more flexible parameters
Almost all composable objects require some type of parameter as input. Usually, this is a reactive ref
. It can also be a primitive Javascript type like string, number or object.
But we want to write more flexible and reusable compositions, so we not only have to receive parameters of type ref
but also primitive type parameters, and then we convert the parameters to the parameters we need. As follows:
// 传递一个 ref
const countRef = ref(2);
useCount(countRef);
// 或者直接一个数字
const countRef = useRef(2);
VueUse useTitle
also adopts this mode.
When we pass in a ref
, the page title can be dynamically changed by .value.
const title = ref('This is the title');
useTitle(title);
title.value = 'New title please';
If a string is passed in, useTitle will create a ref internally with the value of the character we passed in, and finally return a ref variable, and then .value
to dynamically change.
const title = useTitle('This is the title');
title.value = 'New title please';
Implement a flexible parameter in the composition
In order for the flexible parameter mode to work, we need to use the ref
function or the unref
function on the resulting parameter.
export default useMyComposable(input) {
const ref = ref(input);
}
export default useMyComposable(input) {
const rawValue = unref(input);
}
ref
function will create a new one for us ref
. But if we pass it a ref
, it just returns this ref
to us
// 创建一个 ref
const myRef = ref(0);
// 结果是相等的
assert(myRef === ref(myRef));
unref
The function works the same, but it either unwraps a ref
or gives us our original value back.
const value = unref(myRef);
// 结果是相等的
assert(value === unref(value));
Let's see how some combinations in VueUse implement this pattern. VueUse is an open source portfolio collection for Vue 3 that is very well written. It's a great resource for learning how to write composable code
useTitle
Back to useTitle
, which we are already familiar with.
This composable pattern lets us pass in a string or a string of ref
. It doesn't care which one we provide.
// Pass in a string
const titleRef = useTitle('Initial title');
// Pass in a ref of a string
const titleRef = ref('Initial title');
useTitle(titleRef);
In the source code, you can see that after we destructure the options object, we create the title ref. The ref
function is used here, which allows us to use a ref
or a string to create a ref for the title.
// ...
const title = ref(newTitle ?? document?.title ?? null)
// ...
The meaning here is to take newTitle as the initialization value first, if not taking document?.title
, or not, take null
.
For TypeScript users, here are some interesting things to note.
The type of the newTitle
variable used here is MaybeRef<string>
. Here is the definition of this type:
type MaybeRef<T> = T | Ref<T>
This type definition means that the MaybeRef<string>
type can be either a string or a Ref<string>
, which is a ---30be4de3beeaead412a0451a1b1984e4 Ref
with a string value in it.
Let's move on to the next composition that also uses this type to implement this pattern.
useCssVar
useCssVar
Combination allows us to grab the value of a CSS variable and use it in our application.
const backgroundColor = useCssVar('--background-color');
But unlike useTitle
here we need string values so we can look up CSS variables in the DOM. Using the unref
function, this composable function can handle both incoming references and strings.
// Using a string
const backgroundColor = useCssVar('--background-color');
// Using a ref
const cssVarRef = ref('--background-color');
const backgroundColor = useCssVar(cssVarRef);
Looking at the source code , we can see that it uses the unref
function to accomplish this task. Actually, it uses a helper function called unrefElement
to make sure we get a DOM element and not just a Vue instance.
If you want to explore it further, most compositions in VueUse implement this pattern. So, pick one that interests you, and dive into the code.
Summarize
We've just spent some time learning the second pattern in this series, in which we can do this by cleverly using ref
and unref
in our composable program Use parameters more flexibly. Whether you happen to have one ref
or just Javascript's primitive values, synthesizable things will still work. It adapts to how you use it!
We also looked at how the VueUse library implements this pattern in a combination of useTitle
and useCssVar
. useTitle
combining the ref
function, and useCssVar
use the unref
function, so we can see the effect of the two changes.
In the next article, we'll introduce another pattern that improves upon return values by making them dynamic. We'll learn how to return a single value or an object as needed.
// Returns a single value
const isDark = useDark();
// Returns an object of values
const {
counter,
pause,
resume,
} = useInterval(1000, { controls: true });
This pattern can make your composability much simpler to use, especially when you only need a single value most of the time.
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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。