Unable to bring in ES6 module to Vue's single file component

I am currently experimenting with ES6 modules and Vue.js, specifically single file components (SFC). To create my project, I utilized the Vue CLI with the webpack-simple template. I encountered an error that says "TypeError: Cannot read property 'name' of undefined" at the line where "settings.mainAlarm.name" is called. While running "npm run dev" does not generate any errors, I suspect that the build process is locating (and potentially disregarding) the settings.js file. What would be the most effective method for importing 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;
}

Answer №1

Your settings file should be structured like the following:

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

If your component follows this structure, it will function properly. Alternatively, your component can be structured like this:

<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>

It is likely that the first option is what you truly desire (creating a unique settings object every time you use settings may not be necessary).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending information from Axios to Danfo using NextJs is seamless and efficient

I am currently developing a NextJs page where I have incorporated axios along with useState and useEffect to fetch JSON data from a web API and store it in a state called 'apiData'. .then((res) => { setApiData(res.data.Projects); conso ...

Navigate to a Vue router hash without refreshing the component and scroll to it seamlessly

I'm currently utilizing Vue 3 along with vue-router 4. Suppose I have hash links within a component: <router-link :to="{ hash: '#l1' }">Section - 1</router-link> <router-link :to="{ hash: '#l2' }" ...

Possible rephrased version: "Encountering a Jquery clash

It appears that the issue causing my problem may be a Jquery conflict. Please correct me if I am wrong after reviewing the information below. I am new to Jquery and attempting to add a dropdown plugin to a website. The attempt is successful, but an existi ...

Failure encountered when attempting to load JSON data into datalist

I've been trying to incorporate inputs into a datalist in two different ways. However, I've encountered an issue with the first method not working properly. --> Check it out on bootlply var dataList = document.getElementById('json-datal ...

Error: Unable to access 'author' property as it is undefined

Currently, I am in the process of learning how to create my own blog by following a tutorial on Github. The tutorial can be found at https://github.com/adrianhajdin/project_graphql_blog. However, while working with [slug].js to build localhost/3000/post/re ...

Display all items that contain a specified string using JavaScript

I'm in need of some assistance with a problem that I've been struggling with. I have several JavaScript objects containing different data pieces as shown below:- Object {id: 1, shopcounty: "cornwall", shopaddress: "the cycle centre,<br />1 ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

Navigate to a specific div with its id in ReactJS without relying on external libraries

Is it possible to scroll to a specific div using an ID in React without relying on external libraries? I've come across some solutions that involve scroll libraries. Below is the code for the div within my WrappedQuestionFormFinal component: <div ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

What is the best way to implement a sliding animation for a toggle button?

Currently, I am working on a toggle bar element that is functioning correctly in terms of styling the toggled button. However, I would like to add more animation to enhance the user experience. The concept is to have the active button slide to the newly s ...

Navigate a JSON object using JavaScript

As I continue to juggle learning code with my job, I am diving into the world of creating charts using AMcharts. My goal is to generate multiple data sets based on orientation and potentially expand further in the future. In the JSON snippet below, you can ...

Encountering the error message "Uncaught Error: [vuex] Getters must be functions, but 'getters.getters' is {}. This occurred while splitting the Vuex store into modules in Vue.js."

As a beginner in VUEX, I am experimenting with building a test application to dive deeper into the world of VUEX. I have organized my VUEX store into modules, where each module has its own getter.js file. Getters, actions, and mutations are imported into i ...

Trying to assign a value to the property 'male' of an undefined object - error encountered while setting object value from an array

Why is it that when I add one more testObject, the code doesn't work anymore? The line of code where only one testObject is used works fine (testObject[Object.values(testObject)[0]]=5), but adding another testObject causes issues. const testObject ...

How to dynamically bind items in vuejs

I have a basic select that I would like to bind to an array. My framework is Vuetify, but this issue is common across platforms. <v-select v-bind:items="physicianListSpeciality" > </v-select> Now I want to use the same select for multiple arr ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

My redirect is being disrupted by passing a text string with new lines through GET requests

My issue involves submitting a form that utilizes JavaScript to pass a value through GET. Upon reaching the submission page, the function runs successfully, but when redirecting via the header, it ends up on a blank page. The header code for redirection lo ...