Reputation: 5257
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>
Upvotes: 0
Views: 135
Reputation: 2617
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.
Upvotes: 2