比如el-upload中的 :on-success= fn,其实是给组件el-upload传递一个prop,这样写的话fn只能接受upload组件规定的参数,如果想自己传递父组件中的参数比如b,要写成:on-success= ()=>{fn2(b)}
原理要从Vue的render函数的生成讲起
<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数组
element-ui(或者说Vue的子组件)绑定的方法中传入自定义参数
原文:https://www.cnblogs.com/chuliang/p/10770073.html