比如el-upload中的 :on-success= fn,其实是给组件el-upload传递一个prop,这样写的话fn只能接受upload组件规定的参数,如果想自己传递父组件中的参数比如b,要写成:on-success= ()=>{fn2(b)}

原理要从Vue的render函数的生成讲起

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

<child :trans_method="test">点击</child>

这是一个自定义的子组件,它的父组件的render函数是这样的:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('child',{attrs:{"trans_method":test}},[_v("点击")])],1)}
}

这里的this是父组件vm,可以看到子组件将来接受到的trans_method将会是test这个方法

而如果写成<child :trans_method="()=>{fn1(name)}">点击</child>,把匿名函数写到组件属性中

render函数是这样的

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('child',{attrs:{"trans_method":()=>{fn1(name)}}},[_v("点击")])],1)}
}

可见能做到闭包,this和this.name都在trans_method在子组件调用的时候可以找到

再进一步 如果写成这样:

<child v-for="item in array" :trans_method="()=>{fn1(item)}">点击</child>

render函数是这样的:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},_l((array),function(item){return _c('child',{attrs:{"trans_method":()=>{fn1(item)}}},[_v("点击")])}),1)}
}

_l函数是renderList,逻辑是第二个参数(方法)调用array的元素-item,返回_c方法执行后生成的Vnode数组

说句题外话:

如果v-on绑定的不是方法对象而是直接调用方法,那绑定的就是方法的返回值这个没什么说的

但如果是<child @click="test(name)">点击</child>

render函数是这样的:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},[_c('child',{on:{"click":function($event){return test(name)}}},[_v("点击")])],1)}
}

这个也在意料之中,毕竟是传统的on事件

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄