skip to Main Content

Hope you are doing well!

I am working on a vue 3 application which has n number of components. One of the component has a js file inside which there is a js function which is called.
This js function is in external javascript file and it returns a data.
Now how can i catch this data in my vue component?

2

Answers


  1. You should export the function in the external javascript file and then import it in your vue component. Then you can call it and get the data. Here is an example:

    Your external javascript file:

    export function myFunction() {
      // return some data
      return data;
    }
    

    And in your vue component:

    <script setup>
    import { myFunction } from './path/to/external-script.js';
    
    // call your function and get the data
    const data = myFunction();
    </script>
    
    Login or Signup to reply.
  2. Assuming you have an external JavaScript file named external.js with a getData() function that returns data:

    // external.js
    
    function getData() {
      // Your logic to retrieve data
      return "The data you want to retrieve";
    }
    

    In your Vue component, you can import this external file and use the getData() function:

    // YourComponent.vue
    
    <template>
      <div>
        <p>{{ myData }}</p>
      </div>
    </template>
    
    <script>
    import { ref, onMounted } from 'vue';
    import { getData } from './external'; // Make sure to provide the correct path to your external file
    
    export default {
      setup() {
        const myData = ref('');
    
        onMounted(() => {
          // Call the getData() function from the external file
          myData.value = getData();
        });
    
        return {
          myData,
        };
      },
    };
    </script>
    

    getData() is imported from the external.js file.
    myData is a Vue ref that will store the data returned by the external function.
    The onMounted function is used to ensure that the call to getData() occurs after the component has been mounted.

    Make sure to adjust the path to the external file based on your project structure.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search