Home  >  Q&A  >  body text

Vue 3 template references in composables

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?

P粉153503989P粉153503989301 days ago499

reply all(1)I'll reply

  • P粉658954914

    P粉6589549142023-12-23 19:48:00

    Your useGlobalComposable function should return myAlert like 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 that this.$refs in mixin cannot be used directly with the Composition API. If you create a component, you can access component properties and methods using this.

    This is an article about using refs with the Composition API.

    Very simple working example using composable items in settings :

     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')
    <div id="app">
      <div>Test: {{ test }}</div>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

    reply
    0
  • Cancelreply