2017-04-13 38 views
0

是否可以在Vue.JS的另一个组件中声明组件? 这就是我想要做的事:可重复使用的嵌套VueJS组件

<!-- this is declared inside some-component.vue file --> 
<script> 
    export default { 
     components:{ 
      'cmptest' : { 
       template:'#cmptest', 
       props:['mprop'] 
      } 
     }, 
     data :() => ({ 
      val:'world' 
     }) 
    }; 
</script> 

<template> 
    <div> 
     <template id="cmptest"> 
      {{mprop}} 
     </template> 
     <cmptest mprop="hello"></cmptest> 
     <cmptest :mprop="val"></cmptest> 
    </div> 
</template> 

我想避免全球注册的子组件(如果可能与Vue.component(...)

换句话说,我想说明孩子的<template>里面的父组件文件(没有做一个巨大的线template:'entire-html-of-child-component-here'

+0

现在我用的巨大的一行'模板:“......”',它工作正常,但如果有谁知道没有更好的办法创建额外的文件... – andrei

回答

1

当然。

像这样:

https://jsfiddle.net/wostex/63t082p2/7/

<div id="app"> 
    <app-child myprop="You"></app-child> 
    <app-child myprop="Me"></app-child> 
    <app-child myprop="World"></app-child> 
</div> 

<script type="text/x-template" id="app-child2"> 
    <span style="color: red">{{ text }}</span> 
</script> 

<script type="text/x-template" id="app-child"> 
    <div>{{ childData }} {{ myprop }} <app-child2 text="Again"></app-child2></div> 
</script> 

new Vue({ 
    el: '#app', 
    components: { 
    'app-child': { 
     template: '#app-child', 
     props: ['myprop'], 
     data: function() { 
     return { 
      childData: 'Hello' 
     } 
     }, 
     components: { 
     'app-child2': { 
      template: '#app-child2', 
      props: ['text'] 
     } 
     } 
    } 
    } 
}); 
+0

任何方式来执行它在相同的.vue文件?我只需要在一个.vue(父)文件中使用这个子组件。 – andrei

+0

@andrei你可以做到这一点,检查更新的答案。 – wostex

+0

@wostex我认为你的例子不符合该部分的要求:_换句话说,我想在父组件文件中指定子代的