鍍金池/ 問答/HTML/ vue.js關(guān)于props為函數(shù)的一個疑惑,this指向的是父級

vue.js關(guān)于props為函數(shù)的一個疑惑,this指向的是父級

codepen
點擊按鈕輸出的是父組件的msg:hello,i am peiqi,在子組件里面this為什么會指向父級?
源碼還沒有了解到這里所以不太清楚
代碼如下:

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()
    }
  }
  // 選項
})

補充:8.10有答案說vue對this做了特殊處理

在我的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)
      }
   }
  // 選項
})

確實用call也沒法改變this的指向
猜想是不是可能用了bind如下:

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
回答
編輯回答
忠妾

methods里面的函數(shù)的this已經(jīng)被bind死了 不能修改了 要想給子組件賦值函數(shù)的話 你這樣試試 看看行不行

Vue.component('fff', {
  template:`<div><sss :ff="sfs"></sss></div>`,
  data(){
    return{
      msg:'hello,i am peiqi',
      sfs:function(){
        console.log(this.msg)
      }
    }  
  },
  methods:{
  }
})
2018年2月22日 03:25
編輯回答
過客

vue組件實例化的時候會把定義時的method的函數(shù)bind this到實例上,bind之后this就定死了
所以聲明method的時候一定要用function聲明,不能用箭頭函數(shù)

2018年5月9日 09:36
編輯回答
舊城人

可以看一下這篇博文,可能對你理解有幫助https://segmentfault.com/a/11...

2017年9月3日 18:51
編輯回答
你好胸
//準確的說是此處的this一直指向當前Vue實例,即使是通過call方法也不能改變其上下文,
//this的指向這在Vue官網(wǎng)文檔上是有說的
sf(){
  console.log(this.msg)
}
2017年1月29日 01:37