去评论
海欣资源

vue组件间传值有哪些方法

xx5678
2022/05/06 00:33:37
涓涓剁埗瀛愮粍浠朵紶鍊
    鍏堝湪鐖剁粍浠朵腑缁欏瓙缁勪欢鐨勮嚜瀹氫箟灞炴х粦瀹氫竴涓 鐖剁粍浠剁殑鍙橀噺
<template class="father">
   <child :鑷畾涔夊睘鎬у悕="鐖剁粍浠剁殑鍙橀噺"></child>
<template >
    鍦ㄥ瓙缁勪欢鐨刾rops灞炴т腑鍙互鍙栧嚭鐖剁粍浠剁粰鐨勫硷紝props涓殑鍙橀噺鐢ㄦ硶鍜宒ata涓彉閲忕敤娉曞畬鍏ㄤ竴鏍凤紝鍙笉杩囧肩殑鏉ユ簮涓嶅悓

export default {
        name: "child",
        props: ["鑷畾涔夊睘鎬у悕"],
    data() {}
}

浜屼付瀛愮埗缁勪欢浼犲
    鍏堝湪鐖剁粍浠朵腑缁欏瓙缁勪欢鐨 鑷畾涔夊睘鎬 缁戝畾涓涓埗缁勪欢鐨勫嚱鏁
<template class="father">  
        <child  @鑷畾涔変簨浠="鐖剁殑澶勭悊鍑芥暟">
<template >
export default {
        name: "father",
        data() {}
        methods:{
                鐖剁殑澶勭悊鍑芥暟(鍙傛暟){
            //鍙傛暟锛氬緱鍒板瓙缁勪欢瑙﹀彂浜嬩欢($emit)鏃讹紝浼犻掕繃鏉ョ殑鏁版嵁
        }
    }
})
    鍦ㄥ瓙缁勪欢涓 this.$emit(鈥滅埗鐨勫鐞嗗嚱鏁扳,this.鏁版嵁) 瑙﹀彂鐖剁粍浠朵腑鐨勫嚱鏁拌繘琛屼紶鍙

涓変付鍏勫紵缁勪欢浼犲
浜嬩欢鎬荤嚎:
灏辨槸鍒涘缓涓涓簨浠朵腑蹇冿紝鐩稿綋浜庝腑杞珯锛屽彲浠ョ敤瀹冩潵浼犻掍簨浠跺拰鎺ユ敹浜嬩欢
    鍒涘缓鍏ㄥ眬绌篤ue瀹炰緥锛歟ventBus
import Vue from 'vue';
const eventBus= new Vue()  //鍒涘缓浜嬩欢鎬荤嚎
export default eventBus;
    鍏蜂綋椤甸潰浣跨敤$emit鍙戝竷浜嬩欢 - 浼犻掑
import eventBus from '@u/eventBus'
eventBus.$emit('send',鈥榟ello鈥)
    鍏蜂綋椤甸潰浣跨敤$on璁㈤槄浜嬩欢 - 鎺ユ敹缁勪欢鍊
import eventBus from '@u/eventBus'
eventBus.$on('send', msg => {
        console.log(msg)  //鎺у埗鍙拌緭鍑 hello
}
    娉ㄦ剰锛$on鍏堣繘琛岀洃鍚紝涓鏃$emit鍙戝竷浜嬩欢鍚庢墍鏈夌粍浠堕兘鍙互$on鐩戝惉鍒颁簨浠躲傛墍浠ヤ紶閫掑弬鏁扮殑鏃跺欎竴瀹氬凡缁忓厛杩涜浜嗙洃鍚墠鑳藉緱鍒板弬鏁般傛瘮濡傚湪鐖剁粍浠朵腑$emit浜嬩欢鏀惧湪mounted閽╁瓙鍑芥暟涓紝绛夊緟瀛愮粍浠跺垱寤哄苟$on寮濮嬬洃鍚簨浠跺悗鍐嶅幓瑙﹀彂$emit鍙戝竷浜嬩欢銆
    $off()绉婚櫎浜嬩欢鐩戝惉
import eventBus from '@u/eventBus'
eventBus.$off('send')  
浜嬩欢璁㈤槄鍔熻兘$on鏄$eventBus瀵硅薄瀹屾垚鐨勶紝涓庣粍浠舵棤鍏筹紝濡傛灉鐢╲-if閿姣佸瓙缁勪欢鐨勬椂鍊欙紝浼氬舰鎴愰棴鍖咃紝閫犳垚鍐呭瓨娉勯湶锛屾墍鏈夎鍦ㄩ攢姣佺粍浠剁殑鏃跺欒繘琛屽彇娑堢洃鍚簨浠
鍏蜂綋褰㈡垚鍘熷洜鐐瑰嚮鏌ョ湅

鍥涗付$parent /$children涓巖ef
    $parent鏂规硶鏄湪瀛愮粍浠朵腑鍙互鐩存帴璁块棶璇ョ粍浠剁殑鐖跺疄渚嬫垨缁勪欢銆
    鍦ㄧ埗缁勪欢涓畾涔変竴涓垏鎹㈡樉绀洪〉闈㈡墽琛屼腑鐨勬樉绀烘柟娉曘
switchLoadPage(msg) {
    if(!this.loading && msg)
                  this.loadtext=msg;
                  this.loading = !this.loading;
},
鈥 鍦ㄥ瓙缁勪欢涓洿鎺ラ氳繃$parent鍘昏皟鐢ㄨ鏂规硶
this.$parent.switchLoadPage();
    $children鏂规硶鏄湪鐖剁粍浠朵腑鍙互鐩存帴璁块棶瀛愮粍浠剁殑瀹炰緥锛屼絾鏄笉淇濊瘉瀛愮粍浠剁殑椤哄簭銆
    ref 琚敤鏉ョ粰DOM鍏冪礌鎴栧瓙缁勪欢娉ㄥ唽寮曠敤淇℃伅銆傚紩鐢ㄤ俊鎭細鏍规嵁鐖剁粍浠剁殑 $refs 瀵硅薄杩涜娉ㄥ唽銆傚鏋滃湪鏅氱殑DOM鍏冪礌涓婁娇鐢紝寮曠敤淇℃伅灏辨槸鍏冪礌; 濡傛灉鐢ㄥ湪瀛愮粍浠朵笂锛屽紩鐢ㄤ俊鎭氨鏄粍浠跺疄渚嬨
    鍦ㄧ埗缁勪欢涓嚜瀹氫箟涓涓〃鏍肩粍浠讹紝缁欏瓙缁勪欢鍔犱笂 ref灞炴
<result ref="result" :config="dgConfig"  ></result>
鈥 鍦ㄧ埗缁勪欢涓氨鍙互閫氳繃this.$refs.result鍘绘壘鍒皉esult瀛愮粍浠惰繘琛屾搷浣,姣斿鎶婄埗缁勪欢鐨剆data鐩存帴鏀惧叆瀛愮粍浠朵腑
methods: {
          info(){
                   this.$refs.result.sdata = this.sdata;
    },
}