methods中的this:
普通函数中的this(methods对象中以简写value形式):
<script>
const vm = new Vue({
el: '#root',
data: { // data 中的的数据做数据劫持代理
name:'小五',
},
methods: { // methods 中的函数不做数据劫持代理
fun(event){ // event 事件对象:event.target->event.target.innerText
alert("hi!");
console.log(this); // this 实例 vm:Vue{} (或者为“组件”实例对象)
}
}
})
</script>
箭头函数中的this(methods对象中以key:value形式):
<script>
const vm = new Vue({
el: '#root',
data: {
name:'小五',
},
methods: {
fun:(event)=>{
alert("hi!");
console.log(this); // this 为全局对象 Window:Window{}
}
}
})
</script>
所有被Vue”管理的函数“ 最好写为“普通函数”!
methods传参:
<body>
<div id="root">
<h2>hi{{name}}!</h2>
<!-- 点击时调用回调函数fun -->
<button v-on:click="fun">点击</button>
<button @click="fun($event, 123)">点击</button>
// 1.简写 v-on: -> @;
// 2.函数需要传参时可以加括号 fun(),防止丢失事件对象:事件对象实参以 $event 标识
</div>
</body>
<script>
const vm = new Vue({
el: '#root',
data: {
name:'小五',
},
methods: {
fun(event, num){
alert("hi!");
console.log(event, num); // MouseEvent{}, 123
}
}
})
</script>