It sounds like you're encountering an issue where the reactivity system in Vue isn't updating your template when the model value changes. This can happen for a few reasons, but let's focus on ensuring that the model is properly reactive and that the event listener is correctly updating it.
Here is a revised version of your code with some adjustments to ensure reactivity:
- Ensure that
modelis a reactive reference. - Make sure the event listener is properly set up and cleaned up.
<template>
<button @click="onClick">
{{ model.value ?? 'Nothing selected' }}
</button>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useSelect } from '@/Composables';
const model = ref(null); // Ensure model is a reactive reference
const select = useSelect();
const onClick = () => {
select.begin({
// Options
});
select.bus.on('itemSelected', listener); // Use a named event for clarity
};
const listener = () => {
model.value = select.item.value;
console.log(model.value, select.item.value);
select.bus.off('itemSelected', listener); // Clean up the listener
};
// Clean up the event listener when the component is unmounted
onUnmounted(() => {
select.bus.off('itemSelected', listener);
});
</script>
Explanation:
-
Reactive Reference: Ensure that
modelis a reactive reference by usingref(null). This makesmodelreactive and ensures that changes tomodel.valuewill trigger updates in the template. -
Event Listener: Use a named event (
'itemSelected') for clarity and consistency. This helps in managing the event listeners more effectively. -
Clean Up: Use
onUnmountedto clean up the event listener when the component is unmounted. This prevents potential memory leaks and ensures that the listener is properly removed. -
Template Binding: Use
model.valuein the template to access the reactive value ofmodel.
By making these adjustments, you should see the model value update in the template when the event is emitted and the listener updates the model.