Asked By: Anonymous
I’m new to Vue.js. I found that the binding is not working when the javascript is loaded before the html template.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<a href="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js">https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js</a>_x000D_
<script type="text/javascript">_x000D_
var demo = new Vue({_x000D_
el: '#demo',_x000D_
data: {_x000D_
message: 'Hello Vue.js!'_x000D_
},_x000D_
methods: {_x000D_
speak: function() {alert(this.message);}_x000D_
}_x000D_
})_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="demo">_x000D_
<p>{{message}}</p>_x000D_
<input v-model="message">_x000D_
<button v-on:click.prevent='speak'>speak</button>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
x000D
However, it works when the script is placed after the html template that the vue.js script is bound to.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<a href="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js">https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js</a>_x000D_
</head>_x000D_
<body>_x000D_
<div id="demo">_x000D_
<p>{{message}}</p>_x000D_
<input v-model="message">_x000D_
<button v-on:click.prevent='speak'>speak</button>_x000D_
</div>_x000D_
</body>_x000D_
<script type="text/javascript">_x000D_
var demo = new Vue({_x000D_
el: '#demo',_x000D_
data: {_x000D_
message: 'Hello Vue.js!'_x000D_
},_x000D_
methods: {_x000D_
speak: function() {alert(this.message);}_x000D_
}_x000D_
})_x000D_
</script>_x000D_
</html>
_x000D_
_x000D_
x000D
I guess this problem is analogous to whether to put the code in ready() when using jQuery. I have searched in google about ready() of Vue.js but it is inside the Vue.js instance. Is there a ready() function just like that of jQuery so that I can load the script before the html? Or, must I Vue.js load the script after the html template?
Solution
Answered By: Anonymous
You can use window.onload
for this task.
window.onload = function() {
// your code here
}
Or you can register a function to load
event :
window.addEventListener('load', function() {
// your code here
})