Composable definition in vue file. Is it wrong? #14792
Replies: 2 comments
Inline Composables Inside
|
|
Defining composables inside a Benefits of Inline Composables:
Guidelines for Defining Inline Composables:
<script setup>
import { ref, computed, onMounted, watch } from 'vue';
const props = defineProps({
type: String,
status: String
});
// Pass props reactively as getters
const { remoteValue, isLoading } = useRemoteValue(() => props.type);
</script>
<script>
// Define the composable outside the setup scope
function useRemoteValue(getType) {
const remoteValue = ref(null);
const isLoading = ref(false);
// Watch the getter function for reactivity
watch(getType, (newType) => {
fetchRemoteValue(newType);
});
onMounted(() => fetchRemoteValue(getType()));
function fetchRemoteValue(type) {
// ...
}
return { remoteValue, isLoading };
}
</script> |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a pattern I follow: every time I create a composable to be reused, I create a ".js" file. However, when I create a composable just to separate code/context that won't be shared, I create the definition within the .vue file itself.
Is this considered bad practice? The documentation doesn't make this clear.
Let’s say I have a component
AppDisplayValuethat receives two props:typeandvalue.If the type is
x, the component performs an internal normalization process using multiple layers of logic, such as computed properties, watchers, and other internal transformations.If the type is
y, it follows a completely different flow, where it retrieves a normalized value from the server, something similar to handling relationships.In this scenario, it is still the same component, but with distinct internal behaviors depending on the type used to render the UI.
To improve separation of concerns and make the context clearer
Exemple of functions...
The key point is that these composables are not intended to be reused anywhere else in the application. Because of that, I define them directly inside the same .vue component where they are used (AppDisplayValue).
All reactions