提问者:小点点

导入单个文件组件VueJS


所有人。

我对制作vue组件有一个小小的怀疑。

我不想使用browserify或webpack,因为我使用的是django,它的大部分模板都在静态文件中,尽管我读过这篇文章,其中描述了如何兼顾两者(但那是以后的事情了)。

我正在制作一个文件组件,我必须导入和使用,使用我的路由器,但我不能,因为导入只是没有发生。

你好Vue

<template>
 Some HTML code here.
</template>
<script>
module.exports = {
  data() {
    return {
      coin : []
    }
  },
  beforeRouteEnter (to, from, next) {
    axios.get('my-django-rest-api-url')
    .then(response => {
      next(vm => {
        vm.data = response.data
      })
    })
  }
}
</script>

我把它放在index.html文件中,而不是其他.js文件中,

<script>
    import Hello from '@/components/Hello.vue'
    Vue.use(VueRouter);
    const dashboard = {template:'<p>This is the base template</p>'};
    const profile = {
      template: '#profile_template',
      data () {
        return {
          profile_details: []
        }
      },
      beforeRouteEnter (to, from, next) {
        axios.get('my-api-url')
        .then(response => {
          next(vm => {
            vm.profile_details = response.data
          })
        })
      }
    }
    const router = new VueRouter({
    routes: [
          { path: '/', component: dashboard },
          { path: '/profile', component: profile },
          { path: '/hello', component: Hello }
        ]
    });
    new Vue({
      router : router,
    }).$mount('#app');
</script>

1.并按此处建议删除import语句

  1. **Mozilla(量子57.0.4 64位)**:语法错误:导入声明只能出现在模块的顶层
  2. **Chrome(63.0.3239.108(官方版本)(64位))**:未捕获的语法错误:意外的标识符

共2个答案

匿名用户

不是Vue.js大师,但这里有几个观点可能会对您有所帮助。

  • 现代浏览器默认情况下仍不支持模块加载,您需要设置特殊标志才能启用它(应用程序的用户可能不会这样做)。
  • 如果坚持使用导入导出,则需要WebPack。当然还有Babel(或任何其他ES6 transpiler,例如Buble)
  • 如果您更喜欢module.exports,那么您需要Browserify。它支持浏览器环境中的CommonJS。
  • 如果两者都不可行,那么最好的方法是在全局范围内定义Vue组件。您可以将它们拆分到不同的文件中,并分别用