情景:
父組件中引入上傳附件的子組件:點(diǎn)擊組件可以分別上傳對(duì)應(yīng)要求的圖片,子組件內(nèi)部循環(huán)可創(chuàng)建多個(gè)模塊.
父組件傳入數(shù)組子組件循環(huán)來(lái)創(chuàng)建不同的組件模塊,所有事件都在子組件內(nèi)部.
父組件頁(yè)面的上方同時(shí)有一個(gè)上傳圖片按鈕上傳圖片后會(huì)顯示在第一個(gè)模塊:
設(shè)想思路:點(diǎn)擊父組件中的按鈕觸發(fā)子組件中上傳方法:
子組件上定義ref="refName",
父組件的方法中用this.$refs.refName.method
去調(diào)用子組件方法
子組件中處理上傳的方法:
fileClick(index) { console.log('子組件的fileClick被調(diào)用了') console.log('index: '+index) // this.aaa(); if(!this.fileInfor[index].imgUrl){ //如果當(dāng)前框里沒(méi)有圖片,則實(shí)現(xiàn)上傳 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中定義方法,同時(shí)傳入相應(yīng)的index值.
Upload(){ // console.log('父組件的xiechengUpload被調(diào)用了') this.$refs.uploadRef.fileClick(0); },
此時(shí)就可以通過(guò)上傳按鈕將圖片放到子組件的第一個(gè)模塊中了.
下面看下Vue父組件調(diào)用子組件事件
Vue父組件向子組件傳遞事件/調(diào)用事件
不是傳遞數(shù)據(jù)(props)哦,適用于 Vue 2.0
方法一:子組件監(jiān)聽(tīng)父組件發(fā)送的方法
方法二:父組件調(diào)用子組件方法
子組件:
export default { mounted: function () { this.$nextTick(function () { this.$on('childMethod', function () { console.log('監(jiān)聽(tīng)成功') }) }) }, methods { callMethod () { console.log('調(diào)用成功') } } }
父組件:
<child ref="child" @click="click"></child> export default { methods: { click () { this.$refs.child.$emit('childMethod') // 方法1 this.$refs.child.callMethod() // 方法2 }, components: { child: child } }
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
源生JS實(shí)現(xiàn)文件拖拽事件
vue全局局部組件使用詳解
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com