Vue 3 template references in composables
David Beckham
David Beckham 2023-12-22 22:57:26
0
1
471

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 

May I? If so, how should I declare the myAlert template reference in the composable?

David Beckham
David Beckham

reply all (1)
P粉658954914

YouruseGlobalComposablefunction should returnmyAlertlike this:

const useGlobalComposable = function() { const myAlertDiv = .... const myAlert = computed(() => { return myAlertDiv; }); return {myAlert} }

You can then declare myAlert

in the settings block
const { myAlert } = useComposable(); return { myAlert }

Please note thatthis.$refsinmixincannot be used directly with the Composition API. If you create a component, you can access component properties and methods usingthis.

This is an article aboutusingrefswith the Composition API.

Very simple working example using composable items insettings:

const { ref, reactive, createApp } = Vue; const useComposable = function() { const test = ref(1); return { test }; } const App = { setup() { const { test } = useComposable(); return { test } } } const app = createApp(App) app.mount('#app')
Test: {{ test }}
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!