Home > OS >  Dynamically import functions into a component with Vue 3
Dynamically import functions into a component with Vue 3

Time:10-03

I would like to dynamically (not statically) import functions into a component inside <script setup> ... </script>

Functions are in a pme-check.js file.

import { useStore } from 'vuex';

const store = useStore();

function foo() {
  console.log('foo');
}

function bar() {
 console.log('bar');
}

export { foo, bar };

In the component, I dynamically import my functions like this and it works correctly

import(`../composables/profil/${store.state.formation.profil}-check`).then(
  (module) => {
    console.log(module.foo());
    // -> 'foo'
    console.log(module.bar());
    // -> 'bar
  }
);

But in this way, my functions cannot be accessed by name in the component.

How to get foo() and bar() anywhere in the <script setup> tags of the component.

Thank you

CodePudding user response:

If you want to use foo() and bar() anywhere in the file then you should use require instead of import and the code should look like this:

const profil= require(`../modules/${store.state.profil}`);
// once you required it, you can use it in any place in the component.
profil.foo();
profil.bar();

Everything works for me in Vue 3.

CodePudding user response:

You can assign the imported functions to refs 1️⃣, and then use the functions through the ref's value 2️⃣:

<script setup>
import { ref, watchEffect } from 'vue'

let foo = ref()
let bar = ref()

watchEffect(() => {
  import(`../composables/profil/${store.state.formation.profil}-check`)
    .then((module) => {
      1️⃣
      foo.value = module.foo
      bar.value = module.bar
    })
})

const fooAndBar = () => {
  2️⃣
  foo.value()
  bar.value()
}
</script>

demo

  • Related