eslint-plugin-vue icon indicating copy to clipboard operation
eslint-plugin-vue copied to clipboard

feat(no-ref-as-operand): support ref detection from composable functions

Open kzhrk opened this issue 4 weeks ago • 1 comments

Closes #2519

Summary

Extends the vue/no-ref-as-operand rule to detect and report when ref objects returned from composable functions are used without accessing the .value property.

Previously, the rule only detected direct ref declarations like ref(0). Now it also detects ref objects returned from composable functions:

// ❌ Before: No warning (bug)
const ok = useOk() // returns Ref<boolean>
const msg = ok ? 'yes' : 'no' // No warning was shown

// ✅ After: Warning shown
const ok = useOk() // returns Ref<boolean>
const msg = ok ? 'yes' : 'no' // Warning: Must use `.value` to read or write the value wrapped by `useOk()`.

Motivation

Composable functions are a common pattern in Vue 3 for code reuse. When they return Ref objects, developers should use the .value property to access the wrapped value. However, the rule previously had no way to detect when these composable-returned refs were used incorrectly.

This enhancement provides early feedback to developers, helping them follow Vue 3 best practices and preventing subtle bugs.

Implementation Details

  • Function body analysis: Uses AST analysis to detect when functions return ref objects
  • Pattern support: Handles multiple return patterns:
    • Direct ref() calls: return ref(0)
    • Object properties: return { data: ref(0) }
    • Array elements: return [ref(0)]
  • All scope contexts: Properly searches all scopes to find function definitions
  • Error messages: Shows composable function names in error messages for clarity

Scope and Limitations

The detection works for composable functions defined in the same file. Due to ESLint's single-file analysis model, composable functions imported from external modules cannot be analyzed. This is a fundamental ESLint framework constraint.

Testing

  • Added 6 comprehensive test cases covering:
    • Simple composable functions returning ref
    • Arrow functions returning ref
    • Array destructuring from composable returns
    • Proper .value access detection
    • Error detection when .value is missing
  • All 55 tests pass (49 existing + 6 new)
  • No breaking changes to existing functionality

kzhrk avatar Nov 13 '25 14:11 kzhrk