Skip to content

Rule proposal: no-ref-emit #2601

Closed
@mattjcj

Description

@mattjcj

Hello, first of all thanks for everything provided so far 😃

Please describe what the rule should do:

Reports when trying to emit a ref itself, instead of emitting the value of the ref.

What category should the rule belong to?

  • Enforces code style (layout)
  • 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:

Example 1

<template>
    <button @click="increment">Increment</button>
</template>

<script setup>
import { ref } from vue

const emit = defineEmits(['incremented'])

const counter = ref(0)

function increment() {
    counter.value++
    /* Probably an error, trying to emit a ref instead of it's value. */
    emit('incremented', counter) /* ✗ BAD */
    emit('incremented', counter.value) /* ✓ GOOD */
}
</script>

Example 2

<template>
    <button @click="counterA++">Increment A</button>
    <button @click="counterB++">Increment B</button>
</template>

<script setup>
import { ref, computed, watch } from vue

const emit = defineEmits(['updated'])

const counterA = ref(0)
const counterB = ref(0)

const result = computed(() => ({
    a: counterA.value,
    b: counterB.value,
}))

watch(result, () => {
    /*
    Probably an error, trying to emit a ref instead of it's value.
    Additionally, the parent might try to mutate the emitted value in this case where
    it should be a plain object but is instead a computed ref.
    Ideally we would use the argument provided by the watcher in this specific case though.
    */
    emit('updated', result) /* ✗ BAD */
    emit('updated', result.value) /* ✓ GOOD */
})
</script>

Additional context

I couldn't think of any usecase that's not against Vue recommendations where emitting the ref itself would be justified, but
if there is any feel free to discard this rule proposal.

Maybe this functionality can be added to no-ref-as-operand instead of creating a new rule as it is quite similar ?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions