1.组件使用$attrs和$listeners传递参数时:
发现v-bind和v-on都不好用了,因为$attrs的本质就是父级传递过来的所有参数,试了试直接扩展attrs也就是这么写{...$attrs}并没效果,实际解决方案如下
v-bind = '$attrs' => {...{attrs:this.\$attrs}}
v-on = '$listeners' => {...{on:this.\$listeners}}
解决思路为,去看源码$attrs和$listeners的赋值过程,然后开始猜~
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
...
vm.$attrs = parentVnode.data.attrs || emptyObject;
vm.$listeners = listeners || emptyObject;
...
}
...
updateChildComponent(
child,
options.propsData,
options.listeners,
vnode,
options.children
);
...
this.listeners = data.on || emptyObject;
2.组件使用.sync语法糖传递参数时(比如element的el-dialog组件会使用:visible.sync="dialogVisible"
// template的sync语法糖:
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<span>内容</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="confirmUnbind">确 定</el-button>
</span>
</el-dialog>
// template非语法糖
<el-dialog title="提示" :visible="dialogVisible" @update:visible = "val => this.dialogVisible = val" width="30%">
// JSX 这么写
<el-dialog title="提示" visible={this.dialogVisible} {...{on:{'update:visible': val => this.dialogVisible = val}}} width="30%">
<span>内容</span>
<span slot="footer" class="dialog-footer">
<el-button onClick={()=>...}>取 消</el-button>
<el-button type="primary" onClick={xxx函数名}>确 定</el-button>
</span>
</el-dialog>