1
type Items = string[]
const list = ref<Items>([])

const items = computed({
  get: () => list.value,
  set: (items: Items) => {
    list.value = items
  },
})

This is my computed property with a setter. My question is: Why am I returned a Ref<readonly string[]> when I provide a setter? I would expect items to have type Ref<string[]>

4

2 回答 2

1

The documentation is imprecise on computed types (it mentions Ref<T> instead of Ref<Readonly<T>>) but explains the difference between readonly and changeable computed property:

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.

The real types are:

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[]>> type means that ref value can be reassigned like ref.value = items but not mutated like ref.value[0] = item.

于 2020-04-10T10:14:14.563 回答
0

For this cases, you should use WritableComputedRef<T>, becouse, when we use only ComputedRef it's only for read, not for write.

E.g

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;
  }
};
于 2021-08-03T16:26:25.887 回答