簡體   English   中英

導入單個文件組件 VueJS

[英]Importing single file components VueJS

每個人。

我對制作 vue 組件有一個微不足道的疑問。

我不想使用browserifywebpack ,因為我在 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. <script src="../components/Hello.js" type="module"></script>並按照此處的建議刪除導入語句

  1. 用以下代碼替換我的Hello.js代碼: export const Hello = { ...
  2. 制作一個Hello.js文件並像這樣導入它import Hello from '../components/Hello.js';

錯誤 :

  1. **Mozilla(Quantum 57.0.4 64 位)**:語法錯誤SyntaxError: import declarations may only appear at top level of a module
  2. **Chrome ( 63.0.3239.108 (Official Build) (64-bit) ) ** : Uncaught SyntaxError: Unexpected identifier
PS:我已經嘗試過各種組合

不是 Vue.js 大師,但這里有一些可能對您有所幫助的觀點。

  • 現代瀏覽器默認仍然不支持模塊加載,您需要設置特殊標志才能啟用它(您的應用程序的用戶可能不會這樣做)。
  • 如果您堅持使用importexport ,則需要 Webpack。 當然還有 Babel(或任何其他 ES6 轉譯器,例如Buble )。
  • 如果您更喜歡module.exports ,那么您需要 Browserify。 它支持瀏覽器環境中的 CommonJS。
  • 如果兩者都不可行,那么最好的辦法是在全局范圍內定義 Vue 組件。 您可以將它們拆分為單獨的文件,並使用<script>單獨導入每個文件。 絕對不是最干凈的方法。
  • 單個文件組件通常位於.vue文件中,但無論哪種方式,它們都需要vue-loader ,可以使用捆綁程序(再次)添加和配置。
  • 最后一個選項是僅使用現有的設置,如果有的話(有嗎?)。 如果您已經有 RequireJS、UMD 或類似的東西,請調整您的組件以適應它。 否則,使用<script> s。

你正在嘗試做一些不可能的事情。 Web 瀏覽器不支持將 Vue 單文件組件作為原始組件文件。 應該編譯單個文件組件。

有關更多信息,請參閱: https ://v2.vuejs.org/v2/guide/single-file-components.html

在 Webpack 中,每個文件都可以在包含在包中之前由“加載器”進行轉換,並且 Vue 提供了 vue-loader 插件來翻譯單文件 (.vue) 組件。

vue 單文件組件首先被“翻譯”(編譯)為可供瀏覽器使用的純 JavaScript 代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM