首先说结论,Vue中的methods方法this在源码中全部被bind到当前Vue组件实例,上源码
可以看出vue里面的方法都被bind强制绑定了this上下文,也就是当前Vue组件实例
function nativeBind(fn, ctx) { return fn.bind(ctx)
}
var bind = Function.prototype.bind ? nativeBind : polyfillBind;function initMethods(vm, methods) { //...
for(var key in methods) {
{
//一系列错误检查...
}
vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
}
}
案例一、eventBus传递值
组件B往组件A里面通过eventBus传值
var eventBus = new Vue()
var ComponentA = {
data: function () {
return {
name: "组件A"
}
},
template: '<div id="test1">组件A</div>',
methods: {
test: function () {
console.log(this)
console.log(this.name)
},
},
mounted: function () {
eventBus.$on("test",this.test);
}
}
var ComponentB = {
template: '<div id="test2">组件B</div>',
mounted: function () {
eventBus.$emit("test")
}
}
new Vue({
el: "#app",
components: {
ComponentA,
ComponentB
},
})
组件A中使用eventBus.$on直接绑定methods中的test方法,打印出来的this不是指向调用该test方法的eventBus实例, 而是指向的组件实例A

案例二、原生dom中addListenser
var ComponentA = {
data: function () {
return {
name: "组件A"
}
},
template: '<div id="test1">组件A</div>',
methods: {
test: function () {
console.log(this)
console.log(this.name)
},
},
mounted: function () {
// eventBus.$on("test",this.test);
document.querySelector("#test1").addEventListener("click", this.test)
}
}
正常情况下addlistener中this应该指向监听的t的dom节点,但此时打印出来的this仍然指向组件A的实例对象

本文详细解析了Vue框架中methods内的方法如何通过bind确保this始终指向当前Vue组件实例。通过两个具体案例说明了这一机制的实际应用,包括通过EventBus传递值和在原生DOM中使用addEventListener。

1410

被折叠的 条评论
为什么被折叠?



