2016-12-16 32 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> 
相關問題