Vue.js 's doubt that props is a function. This points to the parent.

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
Apr.07,2021

//thisVuecall
//thisVue
sf(){
  console.log(this.msg)
}

you can take a look at this blog post, which may help you understand https://codeshelper.com/a/11.


when the vue component instantiates, it bind this the defined method function to the instance, and after bind, this is determined to be
, so be sure to declare method with function declaration. Cannot use arrow function


The this of the function in

methods has been killed by bind and cannot be modified. If you want to assign a function to a subcomponent, try this and see if it works

.
Vue.component('fff', {
  template:`<div><sss :ff="sfs"></sss></div>`,
  data(){
    return{
      msg:'hello,i am peiqi',
      sfs:function(){
        console.log(this.msg)
      }
    }  
  },
  methods:{
  }
})
Menu