【问题标题】:Vue complains it can't find child componentVue 抱怨找不到子组件
【发布时间】:2018-10-08 20:49:00
【问题描述】:

我正在尝试重用一个组件 app-address2 作为另一个名为 app-delivery-creation2 的子组件。

错误信息:

vue.js:597 [Vue 警告]:找不到元素:#app-address2

这是我的主要 html 文件:

<div id="app-delivery-creation2">
    <delivery-creation2></delivery-creation2>
</div>

<script src="../assets/js/address.component2.js"></script>
<script src="../assets/js/delivery-creation.component2.js"></script>

这些是组件

Vue.component('form-address2', {
    template: '<div>child component</div>'
})
var appAddress = new Vue({
    el : '#app-address2'
})

Vue.component('delivery-creation2', {
    template :
        '<div class="container">' +
        '       <div id="app-address2">' +
        '           <form-address2></form-address2>' +
        '       </div>' +
        '</div>'
})
var appDeliveryCreation = new Vue({
    el : '#app-delivery-creation2'
})

问题:为什么 vue 说它找不到元素 app-address2?

非常感谢

【问题讨论】:

  • 为什么要将appAddress作为变量?

标签: vue.js vuejs2


【解决方案1】:

当你执行时:

var appAddress = new Vue({
    el : '#app-address2'
})

id 为 app-address2 的元素必须已经已经在 DOM 中。

但是由于您没有直接在页面中声明元素(就像您使用 &lt;div id="app-delivery-creation2"&gt; 一样),所以它不起作用。请注意,您将其声明为另一个组件模板的一部分:

Vue.component('delivery-creation2', {
    template :
        '<div class="container">' +
        '       <div id="app-address2">' +
        '           <form-address2></form-address2>' +
        '       </div>' +
        '</div>'
})

这意味着&lt;div id="app-address2"&gt; 只会在 这段代码执行之后出现在 DOM 中:

var appDeliveryCreation = new Vue({
    el : '#app-delivery-creation2'
})

因为&lt;div id="app-delivery-creation2"&gt; 使用&lt;delivery-creation2&gt;,所以在使用时会将&lt;div id="app-address2"&gt;“附加”到DOM。

换句话说,要使您的代码正常工作,您必须让 var appAddress = new Vue({ 仅在 var appDeliveryCreation = new Vue({ 位之后运行,例如:

var appDeliveryCreation = new Vue({
    el : '#app-delivery-creation2'
})
var appAddress = new Vue({
    el : '#app-address2'
})

虽然它可能会奏效,但这似乎是一些疯狂的想法。 FWIW,你可能想做点别的事情。

【讨论】:

    【解决方案2】:

    好的,我的问题是每个文件导入都在创建一个新的 vue 父实例,这让 vue 感到困惑......

    更多详情here

    这解决了问题

    主 HTML 文件 - 导入 vue 组件

    <div id="app-delivery-creation2">
        <delivery-creation2></delivery-creation2>
    </div>
    
    <script src="../assets/js/address.component2.js"></script>
    <script src="../assets/js/delivery-creation.component2.js"></script>
    

    address.component2.js

    Vue.component('form-address2', {
        template: '<div>child component</div>'
    })
    

    delivery-creation.component2.js

    Vue.component('delivery-creation2', {
        template :
            '<div class="container">' +
            '           <form-address2></form-address2>' +
            '</div>'
    })
    var appDeliveryCreation = new Vue({
        el : '#app-delivery-creation2'
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-12
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 2021-07-29
      • 2016-07-08
      • 1970-01-01
      相关资源
      最近更新 更多