箭头函数:不使用this
场景:定时器;数组里面的一堆方法foreach、map、filter
代码块输出undifind
<div id="app">
<button @click="fun">按钮</button>
<h1>{{msg}}</h1>
</div>
<script src="vue.js"></script>
<script>
const vm = new Vue({
el:'#app',
data:{
msg:'我是一个名字',
},
methods:{
fun:()=>{
console.log(this.msg)
}
}
});
</script>
普通函数:可使用this,指向对象
当确定想要用this的时候,就不能用箭头函数
对于对象的方法,不能使用箭头函数
点击按钮输出”我是一个名字“
<div id="app">
<button @click="fun">按钮</button>
<h1>{{msg}}</h1>
</div>
<script src="vue.js"></script>
<script>
const vm = new Vue({
el:'#app',
data:{
msg:'我是一个名字',
},
methods:{
fun(){
console.log(this.msg);
}
}
});
</script>