I want to switch from the options API to the composition API and use composables instead of mixins. So far I've been using a global mixin with computed properties like this:
// globalMixin.js computed: { myAlert() { return this.$refs.myAlertDiv; } }
Then I used this mixin when creating the application:
// MyApp.js const MyApp = { mixins: [globalMixin] ... }
myAlert becomes a computed property of MyApp and I can use it without declaring it directly inside the MyApp property.
Now I want to achieve the same result using composables, let's say I have a component that imports composables:
// App.vue <script setup> import { useGlobalComposable} from './globalComposable.js'; const globalComposable = useGlobalComposable(); onMounted(() => { // should work without declaring myAlert inside App.vue console.log(globalComposable.myAlert); }) ... </script>
May I? If so, how should I declare the myAlert template reference in the composable?
Your
useGlobalComposable
function should returnmyAlert
like this:You can then declare myAlert
in the settings blockPlease note that
this.$refs
inmixin
cannot be used directly with the Composition API. If you create a component, you can access component properties and methods usingthis
.This is an article about using
refs
with the Composition API.Very simple working example using composable items in
settings
: