大家好,我带着另一个愚蠢的问题回来了,但我很挣扎,所以我决定问社区。我尝试学习 vue.js 并参与一些非常小的元素。
所以我尝试在页面中间放置一个加载器并在加载完成时显示“页面内容”这是 w3schools 的一个简单示例,我想使用 vue.js 实现它
我得到了这种错误。我做得不好吗?提前谢谢你!
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'showPage' of undefined"
var app = new Vue({
el: "#app",
data: {
myVar: 0,
},
mounted: function() {
this.myFunction() //method will execute at pageload
},
methods: {
showPage: function() {
document.getElementById("loader").style.display = "none";
document.getElementById("myDiv").style.display = "block";
},
myFunction: function() {
myVar = setTimeout(app.showPage, 3000);
},
}
})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Center the loader */
#loader {
position: absolute;
left: 50%;
top: 50%;
z-index: 1;
width: 150px;
height: 150px;
margin: -75px 0 0 -75px;
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 120px;
height: 120px;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
}
@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
/* Add animation to "page content" */
.animate-bottom {
position: relative;
-webkit-animation-name: animatebottom;
-webkit-animation-duration: 1s;
animation-name: animatebottom;
animation-duration: 1s
}
@-webkit-keyframes animatebottom {
from {
bottom: -100px;
opacity: 0
}
to {
bottom: 0px;
opacity: 1
}
}
@keyframes animatebottom {
from {
bottom: -100px;
opacity: 0
}
to {
bottom: 0;
opacity: 1
}
}
#myDiv {
display: none;
text-align: center;
}
</style>
</head>
<body onload="" style="margin:0;">
<div id="app">
<div id="loader"></div>
<div style="display:none;" id="myDiv" class="animate-bottom">
<h2>Tada!</h2>
<p>Some text in my newly loaded page..</p>
</div>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="test.js"></script>
</body>
</html>
最佳答案
关于 docs
All lifecycle hooks are called with their this context pointing to the Vue instance invoking it
所以只需在 myFunction
主体中使用 this.showPage
而不是 app.showPage
关于javascript - 安装方法 - Vue.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53458958/