代码之家  ›  专栏  ›  技术社区  ›  Mark Dalsaso

无法将ES6模块导入Vue单文件组件

  •  4
  • Mark Dalsaso  · 技术社区  · 8 年前

    我正在学习(修补)ES6模块和Vue。js,单文件组件(SFC)。我通过webpack简单模板使用Vue CLI构建了我的项目。我在带有“settings.mainarm.name”的行中遇到错误“TypeError:无法读取未定义的属性‘name’”。“npm run dev”不会抛出任何错误,因此我相信构建步骤正在查找(或者忽略)设置。js文件。将可重用JavaScript导入Vue SFC的最佳方法是什么?

    根vue文件:

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

    ./库/设置。js文件:

    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 回复  |  直到 8 年前
        1
  •  4
  •   Bert Jeffrey Shen    8 年前

    您的设置文件应如下所示

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

    在这种情况下,您的组件将按原样工作,或者您的组件应该是这样的,您可以不使用设置文件

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

    我想这是你的第一选择 真正地 want(我不知道为什么每次使用设置时都需要一个唯一的设置对象,这是您问题中的代码所要做的)。

    推荐文章