Reputation: 5671
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>
<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>
However, it works when the script is placed after the html template that the vue.js script is bound to.
<!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>
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?
Upvotes: 4
Views: 3078
Reputation: 6298
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
})
Upvotes: 5