4

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?

1 Answer 1

5

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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.