简体   繁体   English

Vue.js - 在单个文件组件中使用子组件

[英]Vue.js - Using Child Components in a Single File Component

I have a Vue.js app.我有一个 Vue.js 应用程序。 In this app, I have a single file component .在这个应用程序中,我有一个文件组件 In this component, I want to have another component that's specific to the component.在这个组件中,我想要另一个特定于该组件的组件。 I'm trying to do something like this:我正在尝试做这样的事情:

parent.vue父.vue

<template>
  <div>
    <child-component></child-component><br />
    <child-component></child-component>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        info: 'hello'
      }
    },

    components: {
      childComponent: {
        template: '<div>child</div>',
        data() { return {}; }
      }
    }
  }
</script>

After building with webpack, I then run my app in the browser.使用 webpack 构建后,我在浏览器中运行我的应用程序。 That app then generates an error in the console window that says:然后,该应用程序会在控制台窗口中生成一个错误,上面写着:

Unknown custom element: - did you register the component correctly?未知的自定义元素: - 您是否正确注册了组件?

I believe I've set this up properly.我相信我已经正确设置了这个。 However, clearly I haven't.但是,显然我没有。 What am I doing wrong?我究竟做错了什么? I can see where I may not have registered "child-component".我可以看到我可能没有注册“子组件”的地方。 However, I guess I'm not sure how to do that within a single file component.但是,我想我不确定如何在单个文件组件中执行此操作。 What am I missing?我错过了什么?

Thank you,谢谢,

Some ideas that might be helpful: - as thanksd pointed out, register "child-component" intead of childComponent:一些可能有用的想法: - 正如thanksd指出的那样,注册“child-component”而不是childComponent:

components: {
      "child-component": {
        template: '<div>child</div>',
        data() { return {}; }
      }
    }
  • make sure you register the component before create the vue instance (this may or may not apply to your case, I cannot tell from the source code you posted:确保在创建 vue 实例之前注册组件(这可能适用于您的情况,也可能不适用于您的情况,我无法从您发布的源代码中看出:

    Vue.component(child-component', { template: 'child', data() { return {}; } }) Vue.component(child-component', { template: 'child', data() { return {}; } })

    new Vue({ el: '#app' })新的 Vue({ el: '#app' })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM