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

Rule proposal: Prevent setting nested writable computed value

Open Armaldio opened this issue 2 years ago • 3 comments

Please describe what the rule should do: The rule should warn when trying to set a writable computed ref nested property.

What category should the rule belong to?

  • [ ] Enforces code style (layout)
  • [x] Warns about a potential error (problem)
  • [ ] Suggests an alternate way of doing something (suggestion)
  • [ ] Other (please specify:)

Provide 2-3 code examples that this rule should warn about:

import Vue from 'vue'
import { defineComponent, ref, computed } from '@vue/composition-api'

export default defineComponent({
  setup(props, { root }) {
    const value = ref('French')

    const language = computed({
      get() {
        return {
         	selected: value.value 
        }
      },
      set({ selected }) {
        value.value = selected
      }
    })
    
    console.log(value) // French
    console.log(language) // { selected: 'French' }
    
    // Good
    language.value = { selected: 'English' }
    
    // Bad, it has no effect unlike a standard ref
    language.value.selected = 'German'

    return {
	  language
    }
  }
)}

Additional context

With writable computed ref, it's easy to fall into this case since IDE suggestion will show nested properties.

Armaldio avatar May 16 '22 08:05 Armaldio

Should this maybe also report setting of nested refs? Or is reactivity working as expected in this case?

const myRef = ref({ nested: 'foo' });

myRef.value = { nested: 'bar' }; // GOOD
myRef.value.nested = 'baz' // Maybe BAD? Should maybe use `reactive` instead?

In this case, I'd suggest the rule name vue/no-deep-mutating-refs (since computed returns a ComputedRef or WritableComputedRef).

FloEdelmann avatar May 16 '22 16:05 FloEdelmann

Reactivity is working fine in case of a regular ref

Armaldio avatar May 17 '22 06:05 Armaldio

Thanks for checking. Then I'd suggest rule name vue/no-deep-mutating-computed-ref.

FloEdelmann avatar May 19 '22 09:05 FloEdelmann