0

I am trying to refactor an angular app to Vue in an asp.net mvc app. Following works:

<div id="app" style="margin-top:100px;">
{{message}}
</div>

<script>

 const v = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue.js!'
    }
})

</script>

However when I move the script to a javascript file it dosent work. I guess its some timing in loading the script. What is best practice here?

Layouts: I load following in the laysouts file:

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

<script src="~/Scripts/vue.js"></script>
<script src="~/app/main.js"></script>

</head>
3
  • 1
    Are you loading the script after the div? Commented Oct 6, 2017 at 19:23
  • See the DOMContentLoaded event Commented Oct 6, 2017 at 19:35
  • But is is normal practice with vue to load it in the loaded event? I havent seen anyone doing this. I guess I just as well could use jquery ready? Commented Oct 6, 2017 at 19:38

1 Answer 1

2

Your issue is that you are loading your vue file before the DOM is loaded. It cannot find your id="app" since it hasn't loaded it.

In my projects I have all my html and then load the vue.js file right before the </body> end tag. Like so:

<body>
    <div id="app" style="margin-top:100px;">
        {{message}}
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
    <script src="/myfile.js"></script>
</body>

This is best practice to prevent render blocking scripts. When you put JavaScript in your <head> it has to load those file before the <body> can start rendering.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.