挂载方法-Vue.js

时间:2018-11-24 14:05:06

标签: javascript html css vue.js

大家好,我又提出另一个愚蠢的问题,但我一直在苦苦挣扎,所以我决定问社区。我尝试学习vue.js,然后玩一些很小的小项目。

所以我尝试在页面中间放置一个加载器,并在加载完成后显示“页面内容”,这是w3schools的一个简单示例,我想使用vue.js来实现它。

我得到这种错误。我做得不好吗?预先谢谢您!

  

[Vue警告]:挂接的钩子中出现错误:“ TypeError:无法读取未定义的属性'showPage'”

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>

1 个答案:

答案 0 :(得分:4)

关于docs

  

调用所有生命周期挂钩,并在其上下文中指向调用它的Vue实例

因此,只需在this.showPage正文中使用app.showPage而不是myFunction