[Vuejs]-How to pass a variable from js file to a .vue file

0👍

export the email from the js file then import them from your vue component -inside the script tag- and then you can use it.

0👍

Here is an approach:

// messages.js file
const variableToUseInVue = "hello from a js file"
export default { variableToUseInVue }

Now in your component:

// Hello.vue component
<template>
  <div>
    <p>Message: {{ messages.variableToUseInVue }}</p>
    <!-- Message: hello from a js file -->
  </div>
</template>
<script>
  import messages from './messages' // Import from the js location
  export default {
    data: () => ({ messages: messages })
  }
</script>

A second way is exporting each variable and using object destructuring:

// messages.js file
export const variableToUseInVue = "hello from a js file"

Now in your component:

// Hello.vue component
<template>
  <div>
    <p>Message: {{ variableToUseInVue }}</p>
    <!-- Message: hello from a js file -->
  </div>
</template>
<script>
  import { variableToUseInVue } from './messages' // Import from the js location
  export default {
    data: () => ({ messages: variableToUseInVue })
  }
</script>

Taking in account your requirement, a better approach is to have the login function in Vuex and the user info on it, that way you have access to the information anywhere.

Also, you can have a login component which exposes the email variable and run the login function, the email variable will be reactive and will be updated on change.

Leave a comment