更清洁的方式需要多个Vue组件?

时间:2016-12-16 19:53:19

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

我刚刚开始与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。

3 个答案:

答案 0 :(得分:5)

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>组件,而无需隐式声明它们。

祝你好运:)

答案 1 :(得分:4)

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

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>

答案 2 :(得分:0)

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

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

因此,在组件内部我将使用:

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

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