Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(reactivity): ensure computed wrapped in readonly still works (close #3376) #3377

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion packages/reactivity/__tests__/readonly.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
effect,
ref,
shallowReadonly,
isProxy
isProxy,
computed
} from '../src'

/**
Expand Down Expand Up @@ -435,6 +436,25 @@ describe('reactivity/readonly', () => {
).toHaveBeenWarned()
})

// https://github.com/vuejs/vue-next/issues/3376
test('calling readonly on computed should allow computed to set its private properties', () => {
const r = ref<boolean>(false)
const c = computed(() => r.value)
const rC = readonly(c)

r.value = true

expect(rC.value).toBe(true)
expect(
'Set operation on key "_dirty" failed: target is readonly.'
).not.toHaveBeenWarned()
// @ts-expect-error - non-existant property
rC.randomProperty = true

expect(
'Set operation on key "randomProperty" failed: target is readonly.'
).toHaveBeenWarned()
})
describe('shallowReadonly', () => {
test('should not make non-reactive properties reactive', () => {
const props = shallowReadonly({ n: { foo: 1 } })
Expand Down
8 changes: 7 additions & 1 deletion packages/reactivity/src/baseHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,13 @@ export const mutableHandlers: ProxyHandler<object> = {

export const readonlyHandlers: ProxyHandler<object> = {
get: readonlyGet,
set(target, key) {
set(target, key, value, receiver) {
if ((target as any).__v_isComputed) {
// computed should be able to set its own private properties
if (key === '_dirty' || key === '_value') {
return set(target, key, value, receiver)
}
}
if (__DEV__) {
console.warn(
`Set operation on key "${String(key)}" failed: target is readonly.`,
Expand Down
4 changes: 3 additions & 1 deletion packages/reactivity/src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ class ComputedRefImpl<T> {

public readonly effect: ReactiveEffect<T>

public readonly __v_isRef = true;
public readonly __v_isRef = true
// flag to properly handle computed refs in readonly basehandlers
public readonly __v_isComputed = true;
public readonly [ReactiveFlags.IS_READONLY]: boolean

constructor(
Expand Down