首先说结论,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的实例对象