【问题标题】:Reusable nested VueJS components可重用的嵌套 VueJS 组件
【发布时间】:2023-04-04 01:12:01
【问题描述】:

是否可以在 Vue.JS 中的另一个组件中声明一个组件? 这就是我想要做的:

<!-- 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(...)

换句话说,我想在父组件文件中指定孩子的&lt;template&gt;(不用写一大行template:'entire-html-of-child-component-here'

【问题讨论】:

  • 现在我使用了巨大的单线 template:'....' 并且工作正常,但如果有人知道更好的方法而无需创建额外的文件...

标签: vue.js vuejs2 vue-component


【解决方案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']
        }
      }
    }
  }
});

【讨论】:

  • 有什么方法可以在同一个 .vue 文件中实现吗?我只需要在一个 .vue(父)文件中使用这个子组件。
  • @wostex 我认为您的示例不符合该部分的要求:换句话说,我想在父组件文件 (不做大行模板:'entire-html-of-child-component-here')
  • @donMateo 谢谢,我已经用正确的代码更新了答案。
猜你喜欢
  • 2016-08-13
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2018-08-12
  • 2017-08-06
  • 2017-12-12
相关资源
最近更新 更多