2016-12-16 34 views
2

我刚刚开始使用Vue.JS,并且有一个小问题在困扰着我。更清晰的方式来要求多个Vue组件?

+ 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了。

+0

您不必通过主JS文件中的'Vue.component'列出每个组件 - 这仅适用于全局组件。每个主要组件都可以根据需要使用其自己的子组件,而不会污染根级文件。 https://vuejs.org/v2/guide/components.html – ceejayoz

+0

vue-resource:https://github.com/pagekit/vue-resource –

回答

4

Vue.component语法仅用于全球的部件,如果你有被里面的另一个组件使用使用的组件这样的:

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

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

超过此组件中,您可以使用其他组件。

使用Vue.component(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> 
相关问题