0

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

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

In this case personData acts as global store and it would be better to export it as reactive(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.