The solution provided in the question is correct. In the second example, creating a ref first is the correct approach. This is because the injected object can be either a ref or a plain object, and we need to ensure that we always have a ref to work with.
Here's an example of how this can be done:
<script setup>
import { ref, defineProps, inject } from 'vue'
defineProps({
topic: Object
})
const currentTopic = inject('currentTopic')
// Create a ref if the injected object is not already a ref
const topicRef = ref(currentTopic.value || props.topic)
// Update the injected object when the ref changes
watch(topicRef, (value) => {
currentTopic.value = value
})
// Update the ref when the injected object changes
watch(currentTopic, (value) => {
topicRef.value = value
})
</script>
<template>
<div @click="topicRef = topic" />
</template>
This code creates a ref for the injected object, and then sets up two watchers to keep the ref and the injected object in sync. When the injected object changes, the ref is updated, and when the ref changes, the injected object is updated. This ensures that we always have a ref to work with, regardless of whether the injected object is a ref or a plain object.