[Vue warn]: Cannot find element

前端 未结 6 807
梦如初夏
梦如初夏 2020-12-07 13:22

I\'m using Vuejs. This is my markup:


  
相关标签:
6条回答
  • 2020-12-07 13:56

    I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

    One solution is to place your script in the load event handler like

    window.onload = function () {
        var main = new Vue({
            el: '#main',
            data: {
                currentActivity: 'home'
            }
        });
    }
    

    Another syntax

    window.addEventListener('load', function () {
        //your script
    })
    
    0 讨论(0)
  • 2020-12-07 14:00

    The simple thing is to put the script below the document, just before your closing </body> tag:

    <body>
       <div id="main">
          <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
       </div>
       <script src="app.js"></script>
    </body>
    

    app.js file:

    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
    
    0 讨论(0)
  • 2020-12-07 14:06

    I've solved the problem by add attribute 'defer' to the 'script' element.

    0 讨论(0)
  • 2020-12-07 14:07

    I think sometimes stupid mistakes can give us this error.

    <div id="#main"> <--- id with hashtag
        <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
    </div>
    

    To

    <div id="main"> <--- id without hashtag
        <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
    </div>
    
    0 讨论(0)
  • 2020-12-07 14:17

    You can solve it in two ways.

    1. Make sure you put the CDN into the end of html page and place your own script after that. Example:
        <body>
          <div id="main">
            <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
          </div>
        </body>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
        <script src="js/app.js"></script>
    

    where you need to put same javascript code you wrote in any other JavaScript file or in html file.

    1. Use window.onload function in your JavaScript file.
    0 讨论(0)
  • 2020-12-07 14:20

    I get the same error. the solution is to put your script code before the end of body, not in the head section.

    0 讨论(0)
提交回复
热议问题