为什么这段代码中Mounted后声明的函数没有执行 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="Vue.js"></script> </head> <body> <div id="ert"> <h1 id="45">{{rr}}</h1> </div> <script> new Vue({ el:"#ert", data:{ rr:"23" }, methods:{ m1:function () { console.log("Vue对象初始化完成") } }, beforeCreate:function () { console.log(this.rr) ; this.m1(); }, created:function () { console.log(this.rr); this.m1(); }, beforeMount:function () { var elementById = document.getElementById("45"); console.log(elementById.innerText); }, Mounted:function () { var elementById = document.getElementById("45"); console.log(elementById.innerText); } }) </script> </body> </html>
时间: 2024-01-18 08:05:16 浏览: 22
这段代码中的问题在于,在 Mounted 后声明的函数名为 Mounted,而正确的写法应该是 mounted,即小写字母开头。因此,函数没有被执行。正确的代码应该是:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="Vue.js"></script>
</head>
<body>
<div id="ert">
<h1 id="45">{{rr}}</h1>
</div>
<script>
new Vue({
el:"#ert",
data:{
rr:"23"
},
methods:{
m1:function () {
console.log("Vue对象初始化完成")
}
},
beforeCreate:function () {
console.log(this.rr) ;
this.m1();
},
created:function () {
console.log(this.rr);
this.m1();
},
beforeMount:function () {
var elementById = document.getElementById("45");
console.log(elementById.innerText);
},
mounted:function () {
var elementById = document.getElementById("45");
console.log(elementById.innerText);
}
})
</script>
</body>
</html>
```
这样,mounted 函数就会被正确地执行。