【问题标题】:Cleaner way to require multiple Vue components?需要多个 Vue 组件的更简洁的方法?
【发布时间】:2017-05-02 16:11:06
【问题描述】:

我刚刚开始使用 Vue.JS,有一个小问题困扰着我。我的文件结构类似如下:

+ js
|--+ components
|  |-- parent.vue
|  |-- child.vue
|-- main.js

然后在我的 main.js 中,我有以下内容:

window.Vue = require('vue');
require('vue-resource');
Vue.component('parent', require('./Components/parent'));
Vue.component('child', require('./Components/child'));
var app = new Vue({ el: "#app" });

(我实际上不确定 vue-resource 是什么,但这是通过全新安装的 Laravel 5.3 为我设置的)

乍一看,我立即注意到如果我添加了太多组件,我的 main.js 文件将变得难以管理。我在使用 ReactJS 时没有这个问题,因为 main.js 只需要包含“父”组件,而父组件包含子组件。我认为 Vue.JS 会有一个类似的技巧来帮助我组织我的组件 - 但是阅读我没有找到的文档(也许我错过了它?)

有没有办法或者让 Vue 组件列出其依赖项(以便 Browserify / Webpack 捆绑)在目录中的每个文件上递归地运行 javascript 语句(所以 Browserify / Webpack 只是打包了整个东西)?

我目前不关心异步组件 - 因此,如果解决方案破坏了该功能,那也没关系。有一天,我想尝试使用 Webpack 创建异步组件并仅在需要时加载它们,但今天我更感兴趣的是启动并运行它,这样我就可以玩 Vuex。

【问题讨论】:

标签: javascript webpack vue.js browserify vue-component


【解决方案1】:

Vue.component 语法仅适用于全局组件,如果您有一个正在另一个组件中使用的组件,请使用:

import Parent from './components/Parent.vue';
import Child from './components/Child.vue';

new Vue({ 
  el: "#app", 
  components: { Parent, Child } 
});

在这个组件内部你可以使用其他组件。

使用Vue.component(Parent) 的唯一优点是您可以在所有其他组件中全局使用此<parent></parent> 组件,而无需隐式声明它们。

祝你好运:)

【讨论】:

    【解决方案2】:

    您不需要在顶层导入所有内容。

    在您的main.js 中,您可以导入父组件

    import Parent from './components/Parent.vue'
    
    new Vue({
      el: "#app",
      components: {
        Parent
      }
    })
    

    与您的Parent.vue

    <template>
      <div>
        <p>I am the parent</p>
        <child></child>
      </div>
    </template>
    
    <script>
      import Child from './Child.vue'
    
      export default {
        mounted() {
          console.log('mounted parent')
        }
      }
    </script>
    
    <style scoped>
      // ...
    </style>
    

    然后在你的Child.vue

    <template>
      <p>I am the child</p>
    </template>
    
    <script>
      export default {
        mounted() {
          console.log('mounted child')
        }
      }
    </script>
    
    <style scoped>
      // ...
    </style>
    

    你最终应该得到

    <div>
      <p>I am the parent</p>
      <p>I am the child</p>
    </div>
    

    【讨论】:

      【解决方案3】:

      我找到了一种方法,不确定它在性能和 webpack 块大小方面是否最好。我在组件根目录中创建了一个index.js 文件:

      export const HelloWorld = require('./HelloWorld.vue').default
      

      所以,在我将使用的组件内部:

      const { HelloWorld } = require('@/components')
      

      由于 babel 问题,我需要混合使用 requireexport,还需要在 require 之后使用 default 属性——正如我在一些 babel 使用讨论中所读到的那样。

      【讨论】:

        猜你喜欢
        • 2018-10-05
        • 2013-07-26
        • 2020-03-05
        • 1970-01-01
        • 2014-06-15
        • 1970-01-01
        • 1970-01-01
        • 2020-05-30
        • 1970-01-01
        相关资源
        最近更新 更多