2016-10-30 25 views
10

Ben tek bir dosya bileşenlerin içinde (Vue.component ile) küresel kayıtlı bileşeni kullanmak çalışıyorum ama hepTek dosya bileşenlerinde VueJS 2 global bileşenleri nasıl kullanılır?

Örneğin
vue.common.js:2611[Vue warn]: Unknown custom element: <my-component> - did you register the component correctly? 

alıyorum:

main.js:

... 
Vue.component('my-component', { 
    name: 'my-component', 
    template: '<div>A custom component!</div>' 
}) 
... 

home.vue:

<template> 
    <div> 
     <my-component></my-component> 
    </div> 
</template> 
<script> 
    module.exports = { 
     name: 'home' 
    } 
</script> 
Ben yerel olarak kayıt varsa

, Tamam çalışır:

<template> 
    <div> 
     <my-component></my-component> 
    </div> 
</template> 
<script> 
module.exports = { 
    name: 'home', 
    components: { 
     'my-component': require('./my-component.vue') 
    } 
} 
</script> 
+0

Bileşeni bir yere koymanız gerekiyor, aksi halde indirilmeyecek. – Elfayer

+0

@Elfayer Her şey, Vueify tarafından oluşturulan bir paket içinde ve main.js dosyasında ana bileşen gereklidir. –

cevap

2

Component.vue

<template><div>A custom component!</div></template> 

<script>export default { code here... }</script> 

kullanın home.vue bu bileşen:

<template> 
    <div> 
     <my-component></my-component> 
    </div> 
</template> 

<script> 
    import component from './component.vue' 
    export default { 
    components: { my-component: component } 
    } 
</script> 
+0

Yerel olarak kayıt olmak istemiyorum * my-component *, uygulamanın her yerinde kullanamayacağım ve bu yüzden global olarak * Vue.component * –

21

Sen gerekmez module.exports. Bileşeni global olarak, bu bileşimi, mycomponent.vue dosyasında kaydedebilirsiniz.

<template> 
    <div>A custom component!</div> 
</template> 
<script> 
    export default {} 
</script> 

Sonra

import MyComponent from './component.vue' 
Vue.component('my-component', MyComponent); 

main.js eklemek ya da ben genellikle 'globaller' onları ana alanına içe dosyasını bunları kaydeder.

Bu, benim bileşenimi uygulamada herhangi bir yere kullanmanıza izin vermelidir.

+0

kullanarak kayıt olmak istiyorum. vueify ve ES5. Bu yüzden _module.export_ ve _require_ kullanmalıyım. –

+0

'=', dışa aktarma varsayılan değer olarak kaldırılmalıdır = {} ' – Alexander

+1

Çok teşekkürler. İki gün boyunca, tek sayfalık bir bileşenin küresel olarak nasıl tanımlanacağını anlamaya çalışmak için dokümanlar ve SO'ları okurken harcadım. Sözdizimi sadece Vue.component ('my-component', MyComponent); ':) – Overdrivr

İlgili konular