亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Vue中一個(gè)組件調(diào)用其他組件的方法詳解(非父子組件)

 更新時(shí)間:2022年10月27日 12:12:18   作者:viceen  
vue中最常見(jiàn)子父組件產(chǎn)值,大家一定都很熟悉,最近項(xiàng)目中碰到非父組件中調(diào)用子組件方法的問(wèn)題,這篇文章主要給大家介紹了關(guān)于Vue中一個(gè)組件調(diào)用其他組件的方法(非父子組件),需要的朋友可以參考下

前言

Vue中,一個(gè)組件調(diào)用其他組件的方法(非父子組件)

場(chǎng)景——B頁(yè)面(組件)想調(diào)用 A頁(yè)面(組件)中的方法;但是兩個(gè)頁(yè)面(組件)毫無(wú)關(guān)聯(lián)(刷新 A的數(shù)據(jù))。

方式一:引用式

1、當(dāng)前組件引入將要調(diào)用方法所屬的組件

這里我的當(dāng)前組件要調(diào)用OrderDetail這個(gè)組件的check()方法

import Detail from "./detail.vue";

該方法定義在OrderDetail的methods屬性中

2、當(dāng)前組件通過(guò)該組件methods屬性直接調(diào)用該方法

// 也可以調(diào)用 created、data等
Detail.methods.check();

方式二:vuex

使用 VueX 定義一個(gè)屬性 ,然后在A頁(yè)面 定義一個(gè)計(jì)算屬性(computed) 再把 vuex 的屬性返回給它,再監(jiān)聽(tīng)這個(gè)計(jì)算屬性,發(fā)生變化就調(diào)用你要執(zhí)行的方法。

1、src/store/index.js

//  Vuex   全局
state: { 
	tableStatus:false  
	 	}
 mutations:{  
	changeStatus(state,status) {  //  重復(fù)賦值
      state.tableStatus = status;
    },
}

2、被使用組件- A 頁(yè)面(組件)

 //  A 頁(yè)面(組件)
computed: {  
  status() {  //  計(jì)算屬性
    return this.$store.state.tableStatus; //  Vuex 中定義的屬性
  }
},
watch:{
  status() {
    this.getTableList();  //   需要調(diào)用的方法
  }
},

3、使用觸發(fā)頁(yè)面-B 頁(yè)面(組件)

然后就是在B 頁(yè)面定義一個(gè)點(diǎn)擊事件(舉例),重新給 Vuex中的屬性賦值就行了

//  B頁(yè)面(組件)
closePage() {
    let status = this.$store.state.tableStatus;   // 重新賦值
    this.$store.commit("changeStatus", !status);
},

方式三:使用事件總線(xiàn)eventBus定義全局事件

1、src/main.js

 window.eventBus = new Vue();

2、觸發(fā)頁(yè)面-B組件/發(fā)布事件

window.eventBus.$emit('setFeaturesData', data)  // 帶參數(shù)
window.eventBus.$emit('setFeaturesData')  // 不帶參數(shù)

3、接收頁(yè)面-A組件/訂閱事件

    window.eventBus.$on('setFeaturesData', (data)=>{ // 帶參數(shù)
      this.hoveredFeatures = [data]
      this.onClick()
    })

  mounted() {
    this.getTableData()
    window.eventBus.$on('setFeaturesData', ()=>{ // 不帶參數(shù)
      this.getTableData()
    })
  },

4、移除事件

window.eventBus.$off('setFeaturesData')

總結(jié)

到此這篇關(guān)于Vue中一個(gè)組件調(diào)用其他組件(非父子組件)的文章就介紹到這了,更多相關(guān)Vue組件調(diào)用其他組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論