I write this self-answered question because I have not found a solution on the WEB about the problem that I have detected using Vue.js with ASP.NET MVC 5.
It is a silent error since it did not mark anything in the browser console or at runtime, only that my pages did not work, mainly presenting the following problem:
Selectors correct but not working:
Strange but true, as almost everyone uses _layout.cshtml
mvc in asp.net and within it all my pages are rendered through @RenderBody
.
Pages with this structure:
@{
ViewBag.Title = "opcion";
}
<section class="content-header"></section>
<section class="content">
<div class="box">
"Mi Pagina"
</div>
@section scripts{
<script src="~/Scripts/js/my.js" ></script>
}
</section>
and in my js file I have global selectors, for example:
var text = document.getElementById("unInput");// ||
var algo = $("#otroElemento");
So the problem is that when putting these variables in the console they have a value, that is, they have a selector, but it is a copy of the original element, that is, if I do:
text.value = "Prueba";
My document input doesn't change but if I get the variable value if it has changed in the variable, at first glance it looks as if the changes don't affect the document.
I use vue on me _layout.cshtml
here is a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>@ViewBag.Title - MiSitio</title>
@Styles.Render("~/Content/css")
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
</head>
<body id="vueGlobal">
//Mis elementos
<div class="content">
@RenderBody()
</div>
@Scripts.Render("~/Content/vue")
</body>
</html>
And I have a vue instance in a js document that looks like this:
var vueGlobal = new Vue({
el:"#vueGlobal",
data:{
misDatos: []
},
methods:{
unMetodo: () => console.log("soy un método"),
},
});
Now why do I say the selectors are not functional? They just don't work, I can't add values or use them for anything.
Solution: After days of caffeine and tests I have found the silent problem.
The problem is that the vue instance is having interference with the
@RenderBody()
MVC one since only the selectors inside the view that is loaded with this method suffer from this problem. How did I come to that conclusion?Well, when I delete my instance of vue everything works or if I remove the @RenderBody() obviously.
So the solution was to wait for the document to be ready to proceed to create the vue instance.
It's that simple:
Now the selectors in my child view work and that weird copy isn't created.
Note that this problem will exist if there is a
@RenderBody()
within a vue instance.I hope this saves as much headache as it did for me.