codepen
Click the button to output the msg:hello,i am peiqi, of the parent component. Why does the this point to the parent in the child component?
the source code is not clear here, so the
code is as follows:
Vue.component("fff", {
template:`<div><sss :ff="sf"></sss></div>`,
data(){
return{
msg:"hello,i am peiqi"
}
},
methods:{
sf(){
console.log(this.msg)
}
}
})
Vue.component("sss", {
template:`<button @click="fn">sss</button>`,
props:{
ff:{
type: Function,
required: true
}
},
data(){
return{
msg:","
}
},
methods:{
fn(){
this.ff()
}
}
//
})
add: 8.10 there is an answer that vue has done special treatment to this
change it in my codepen:
Vue.component("sss", {
template:`<div><button @click="fn">sss</button>
<button @click="test">test</button>
</div>`,
props:{
ff:{
type: Function,
required: true
}
},
data(){
return{
msg:","
}
},
methods:{
fn(){
this.ff()
},
test(){
var obj={msg:"obj"}
this.fn.call(this)
this.fn.call(obj)
}
}
//
})
you can"t change the direction of this with call.
guess whether you may have used bind as follows:
a= {name:"z",fn:function(){
console.log(this.name)
}}
b={name:"p"}
a.fn.call(b)
a.fn=a.fn.bind(a)
a.fn.call(b)
// p
// z