1.組件使用$attrs和$listeners傳遞參數(shù)時(shí):
發(fā)現(xiàn)v-bind和v-on都不好用了花沉,因?yàn)?attrs的本質(zhì)就是父級(jí)傳遞過來的所有參數(shù)横缔,試了試直接擴(kuò)展attrs也就是這么寫{...$attrs}并沒效果镜遣,實(shí)際解決方案如下
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語法糖傳遞參數(shù)時(shí)(比如element的el-dialog組件會(huì)使用:visible.sync="dialogVisible"
// template的sync語法糖:
<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
<span>內(nèi)容</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>內(nèi)容</span>
<span slot="footer" class="dialog-footer">
<el-button onClick={()=>...}>取 消</el-button>
<el-button type="primary" onClick={xxx函數(shù)名}>確 定</el-button>
</span>
</el-dialog>