4
votes

I am learning (tinkering with) ES6 modules and Vue.js, single file components (SFC). I built my project with the Vue CLI via the webpack-simple template. I get an error "TypeError: Cannot read property 'name' of undefined" at the line with "settings.mainAlarm.name". "npm run dev" does not throw any errors so I believe the build step is finding (and perhaps ignoring) the settings.js file. What is the best way to import reusable JavaScript into a Vue SFC?

Root.vue file:

<template>
  <div id="app">
    <h1>{{ msg }}</h1>
    <h4>{{ alarmName }}</h4>
  </div>
</template>

<script>
  //const settings =  mainAlarm;
  import settings from './lib/settings.js'

  export default {
    name: 'app',
    data () {
      return {
        msg: 'Welcome to Blah Blah Blah!',
        alarmName: settings.mainAlarm.name
      }
    }
  }
  //console.log(this.alarmName);
</script>

<style>
</style>

./lib/settings.js file:

export default function () {
    var rtn = {
        mainAlarm: {
            name: "overdueCheckAlarm",
            info: {  delayInMinutes: .01,  periodInMinutes: .25  }
        },
        notificationAudioFile: "ache.mp3",
        baseUrl: "www.xxx.com/xx/xxxx-xxx/"
    }
    return rtn;
}
1
You are exporting a function not an object.Bert

1 Answers

4
votes

Either your settings file should look like this

export default {
  mainAlarm: {
    name: "overdueCheckAlarm",
    info: {  delayInMinutes: .01,  periodInMinutes: .25  }
  },
  notificationAudioFile: "ache.mp3",
  baseUrl: "www.xxx.com/xx/xxxx-xxx/"
}

in which case, your component will work as is, or your component should look like this and you can leave the settings file alone

<script>
  import settings from './lib/settings.js'

  // settings.js exports a function as the default, so you
  // need to *call* that function
  const localSettings = settings()

  export default {
    name: 'app',
    data () {
      return {
        msg: 'Welcome to Blah Blah Blah!',
        alarmName: localSettings.mainAlarm.name
      }
    }
  }
</script>

I expect it's the first option you really want (I'm not sure why you would want a unique settings object every time you use settings, which is what the code in your question would do).