情景:
父组件中引入上传附件的子组件:点击组件可以分别上传对应要求的图片,子组件内部循环可创建多个模块.
父组件传入数组子组件循环来创建不同的组件模块,所有事件都在子组件内部.
父组件页面的上方同时有一个上传图片按钮上传图片后会显示在第一个模块:
设想思路:点击父组件中的按钮触发子组件中上传方法:
  子组件上定义ref="refName",父组件的方法中用this.$refs.refName.method去调用子组件方法
子组件中处理上传的方法:
 fileClick(index) {
 console.log('子组件的fileClick被调用了')
 console.log('index: '+index)
 // this.aaa();
 if(!this.fileInfor[index].imgUrl){
 //如果当前框里没有图片,则实现上传
 document.getElementsByClassName('upload_file')[index].click();
 } 
},父组件template
<template> <x-button type="submit" class="custom-primary" @click.native="xiechengUpload">上传图片</x-button> <up-load :fileInformation="fileInformation" ref="uploadRef"></up-load> </template>
父组件method中定义方法,同时传入相应的index值.
Upload(){
 // console.log('父组件的xiechengUpload被调用了')
 this.$refs.uploadRef.fileClick(0);
},此时就可以通过上传按钮将图片放到子组件的第一个模块中了.
下面看下Vue父组件调用子组件事件
Vue父组件向子组件传递事件/调用事件
不是传递数据(props)哦,适用于 Vue 2.0
方法一:子组件监听父组件发送的方法
方法二:父组件调用子组件方法
子组件:
export default {
 mounted: function () {
 this.$nextTick(function () {
 this.$on('childMethod', function () {
 console.log('监听成功')
 })
 })
 },
 methods {
 callMethod () {
 console.log('调用成功')
 }
 }
}父组件:
<child ref="child" @click="click"></child>
export default {
 methods: {
 click () {
 this.$refs.child.$emit('childMethod') // 方法1
 this.$refs.child.callMethod() // 方法2
 },
 components: {
 child: child
 }
}相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
推荐阅读:
源生JS实现文件拖拽事件
vue全局局部组件使用详解
下载本文