简体   繁体   中英

How to use plain javascript variables in vue 3 component?

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM