Home > Back-end >  How to use plain javascript variables in vue 3 component?
How to use plain javascript variables in vue 3 component?

Time:01-01

I have a javascript file with some variables and I want to use them in a vue component like this:

<template>
  <div> Hello {{ personData.name }} {{ personData.last }} </div>
  <button @click="signOut"> Sign Out </button>
</template>

<script>
  import { personData } from '<path>'

  export default {
    ...

    methods: {
      signOut() {
        personData.signed_in = false;
      }
    }
  }
</script>

JS file:

export var personData = {
  name: '<name>',
  last: '<last>',
  signed_in: true,
}

It says personData is undefined but obviously it isn't, and also that it was accessed but not defined on instance. I'm new to Vue so I have no idea what I'm doing wrong. Also its important that they are global and not part of the component

Made nothing appear on the page at all

CodePudding user response:

The problem is, you are importing a variable and just using it inside a Vue instance. VueJS has to know which are reactive data so that it can update the DOM based on its value. So, you make the following changes to make it work:

<template>
  <div> Hello {{ personData.name }} {{ personData.last }} </div>
  <button @click="signOut"> Sign Out </button>
</template>

<script>
  import { personData } from './presonalData.js'
  export default {
    data () {
      return {
        personData  //register as reactive data
      } 
    },
    methods: {
      signOut() {
        personData.signed_in = false;
      }
    }
  }
</script>
  • Related