使用 Function.prototype.bind 为 vuejs 组件的回调函数添加额外参数

文章目录

    在使用 Element UI VueJS 的上传图片组件时,遇到一个问题。需要在一个列表中使用多个 el-upload 组件,当其中一个组件数据更新时(上传成功,或者删除成功),能够及时更新绑定的变量。

    on-success 回调,默认支持的三个参数是

    • res, 上传图片的后台接口返回
    • file, 新增的图片文件
    • fileList,图片列表

    默认是不支持当前循环的 index 。

    解决方法是使用 Function.prototype.bind

    <tr v-for="(item, index) in items" class="array-row">
    	...
    	<el-upload
    			action="/api/upload_image_to_ali"
    			list-type="picture-card"
    			:file-list="item.{{ $prop }}"
    			:on-preview="handlePictureCardPreview"
    			:on-success="handle_image_upload_success.bind(null, {'index':index})"
    			:on-remove="handle_image_remove.bind(null, {'index':index})"
    	>
    	</el-upload>
    
    	<el-dialog :visible.sync="dialogVisible">
    		<img width="100%" :src="dialogImageUrl" alt="">
    	</el-dialog>
    	...
    </tr>
    
    <script>
    ...
    handle_image_upload_success(obj, res, file, fileList) {
    	this.items[obj.index].images.push({url: res.data});
    },
    
    handle_image_remove(obj, file, fileList) {
    	this.items[obj.index].images = fileList;
    },
    ...
    </script>
    

    The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

    非常适合做为定义好参数的回调函数添加额外参数。

    第一个参数为 null 时,应该是不修改原函数的 this。

    参考

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式