为什么 type of computed 属性 Ref<readonly string[]>?
Why is type of computed property Ref<readonly string[]>?
type Items = string[]
const list = ref<Items>([])
const items = computed({
get: () => list.value,
set: (items: Items) => {
list.value = items
},
})
这是我用 setter 计算得出的 属性。我的问题是:为什么我提供 setter 时返回 Ref<readonly string[]>
?我希望项目的类型为 Ref<string[]>
The documentation 在 computed
类型上不精确(它提到 Ref<T>
而不是 Ref<Readonly<T>>
)但解释了只读和可变计算 属性 之间的区别:
Takes a getter function and returns an immutable reactive ref object for the returned value from the getter.
Alternatively, it can take an object with get and set functions to create a writable ref object.
真实的类型是:
export declare function computed<T>(getter: Option<T>['get']): Readonly<Ref<Readonly<T>>>;
export declare function computed<T>(options: Option<T>): Ref<Readonly<T>>;
Ref<Readonly<string[]>>
类型意味着 ref 值可以像 ref.value = items
一样重新分配,但不能像 ref.value[0] = item
.
那样改变
对于这种情况,您应该使用 WritableComputedRef<T>
,因为当我们只使用 ComputedRef
时,它只用于读取,不用于写入。
例如
let showMenu: WritableComputedRef<boolean> = computed({
get: () => props.show,
set: (value: boolean) => {
ctx.emit("update:show", value);
},
});
const handleEscape = (e: KeyboardEvent): void => {
if (e.key === "Esc" || e.key === "Escape") {
showMenu.value = false;
}
};
type Items = string[]
const list = ref<Items>([])
const items = computed({
get: () => list.value,
set: (items: Items) => {
list.value = items
},
})
这是我用 setter 计算得出的 属性。我的问题是:为什么我提供 setter 时返回 Ref<readonly string[]>
?我希望项目的类型为 Ref<string[]>
The documentation 在 computed
类型上不精确(它提到 Ref<T>
而不是 Ref<Readonly<T>>
)但解释了只读和可变计算 属性 之间的区别:
Takes a getter function and returns an immutable reactive ref object for the returned value from the getter.
Alternatively, it can take an object with get and set functions to create a writable ref object.
真实的类型是:
export declare function computed<T>(getter: Option<T>['get']): Readonly<Ref<Readonly<T>>>;
export declare function computed<T>(options: Option<T>): Ref<Readonly<T>>;
Ref<Readonly<string[]>>
类型意味着 ref 值可以像 ref.value = items
一样重新分配,但不能像 ref.value[0] = item
.
对于这种情况,您应该使用 WritableComputedRef<T>
,因为当我们只使用 ComputedRef
时,它只用于读取,不用于写入。
例如
let showMenu: WritableComputedRef<boolean> = computed({
get: () => props.show,
set: (value: boolean) => {
ctx.emit("update:show", value);
},
});
const handleEscape = (e: KeyboardEvent): void => {
if (e.key === "Esc" || e.key === "Escape") {
showMenu.value = false;
}
};