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

更新日期: 2018-12-15 阅读次数: 6611 分类: 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 聊聊, 查看更多联系方式