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

Tim*_*ce7 4 vue.js vue-component vuejs2

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

<!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>
Run Code Online (Sandbox Code Playgroud)

但是,当脚本放在 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>
Run Code Online (Sandbox Code Playgroud)

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

nap*_*zba 5

您可以window.onload用于此任务。

window.onload = function() {
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

或者你可以注册一个函数到loadevent :

window.addEventListener('load', function() {
    // your code here
})
Run Code Online (Sandbox Code Playgroud)