<body>
<div id="app">
<h1>开始练习</h1>
<h2>两秒之后下课</h2>
<button @click="butt">提交</button>
</div>
<script>
const vm = new Vue({
el: '#app',
data() { //只要data中的数据改变,vue一定会重新解析模板
return {
}
},
methods: {
butt(value) {
// setTimeout(() => {
// console.log(this, '下课了');
// }, 2000);
setTimeout(function() {
console.log(this, '下课了');
}, 2000)
}
}
})
</script>
</body>
两秒后输出的结果时window,这是因为定时器所指定的回调函数是由js引擎window所调用的
<body>
<div id="app">
<h1>开始练习</h1>
<h2>两秒之后下课</h2>
<button @click="butt">提交</button>
</div>
<script>
const vm = new Vue({
el: '#app',
data() { //只要data中的数据改变,vue一定会重新解析模板
return {
}
},
methods: {
butt(value) {
setTimeout(() => {
console.log(this, '下课了');
}, 2000);
//setTimeout(function() {
// console.log(this, '下课了');
//}, 2000)
}
}
})
</script>
</body>
两秒后输出的结果是vue,这是因为箭头函数没有自己的this,于是它向外找到的butt()函数的this,而butt函数是vue所管理的函数,所以输出vue