Vue.js 在 html 之前加载脚本时不起作用

Vue.js is not working when script is loaded before html

我是 Vue.js 的新手。我发现当 javascript 在 html 模板之前加载时绑定不起作用。

<!DOCTYPE html>
<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
 <script type="text/javascript">
  var demo = new Vue({
   el: '#demo',
   data: {
    message: 'Hello Vue.js!'
   },
   methods: {
    speak: function() {alert(this.message);}
   }
  })
    </script>
</head>
<body>
 <div id="demo">
  <p>{{message}}</p>
  <input v-model="message">
  <button v-on:click.prevent='speak'>speak</button>
 </div>
</body>

</html>

但是,当脚本放在 vue.js 脚本绑定到的 html 模板之后时,它会起作用。

<!DOCTYPE html>
<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
</head>
<body>
 <div id="demo">
  <p>{{message}}</p>
  <input v-model="message">
  <button v-on:click.prevent='speak'>speak</button>
 </div>
</body>
<script type="text/javascript">
 var demo = new Vue({
  el: '#demo',
  data: {
  message: 'Hello Vue.js!'
  },
  methods: {
  speak: function() {alert(this.message);}
  }
 })
</script>
</html>

我猜这个问题类似于使用jQuery时是否将代码放在ready()中。我在 google 中搜索了 Vue.js 的 ready() 但它在 Vue.js 实例中。是否有与 jQuery 类似的 ready() 函数,以便我可以在 html 之前加载脚本?或者,我必须 Vue.js 在 html 模板之后加载脚本吗?

您可以使用 window.onload 完成此任务。

window.onload = function() {
    // your code here
}

或者您可以向 load 事件注册一个函数:

window.addEventListener('load', function() {
    // your code here
})