簡體   English   中英

Vue.js - 如何從另一個組件調用方法

[英]Vue.js - How to call method from another component

我正在使用 Vue.Js v2。 提交后我想在component2->c2method中調用component1->c1method來重新加載數據。

Vue.component('component1', {
  methods: {
    c1method: function(){
     alert('this is c1method')
    },
  }
})
Vue.component('component2', {
  methods: {
    c2method: function(){
     component('component1').c1method()//like this
    },
  }
})

對於非父子關系,則與此相同。 從任何其他組件調用一個方法,顯然是組件的任何方法。 只需將$on函數添加到$root實例並調用任何其他訪問$root並調用$emit函數的組件。

在第一個組件上

....
    mounted() {
        this.$root.$on('component1', () => {
            // your code goes here
            this.c1method()
        }
    }

並在第二個組件中調用$root中的$emit函數

...
    c2method: function(){
     this.$root.$emit('component1') //like this
    },

它更像是一個套接字。 參考這里

https://stackoverflow.com/a/50343039/6090215

// Component A Vue.component('A', { created() { this.$root.$refs.A = this; }, methods: { foo: function() { alert('this is A.foo'); } } }); // Component B Vue.component('B', { methods: { bar: function() { this.$root.$refs.A.foo(); } } });

無需駭人聽聞的解決方案。
在 vuejs 中,我們可以創建可以全局監聽的事件。
有了這個特性,每當我們想要調用我們鍾愛的函數時,我們就發出這個事件。
現在,我們只是一直從組件中監聽這個事件。 每當這個全局事件發生時,我們就可以執行我們想要調用的方法。

這很簡單:

  1. 你去 main.js,在創建 vue 實例之前,這樣寫:
export const eventBus = new Vue(); // added line


new Vue({
    ...
    ...
    ...
    render: h => h(App)
}).$mount('#app');


  1. 任何我們想觸發目標函數的地方,我們不觸發它,我們只是發出這個事件:
eventBus.$emit('fireMethod');
  1. 現在在我們的具有目標函數的組件中,我們總是監聽這個事件:
created() {
    eventBus.$on('fireMethod', () => {
            this.myBelovedMethod();
    })
}

不要忘記在頂部導入 eventBus。

import {eventBus} from "path/to/main.js";

就是這樣,幾行代碼,沒有hacky,所有vuejs的力量。

文檔解決了這種情況

https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

如果您的組件具有相同的父級,則可以發出父級偵聽的事件。 然后使用ref屬性集,您可以從父級調用c1method

https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs

試試這個。

<template>
 ...
 <component1 ref='componentOne'>
...
</template>
<script>
  Vue.component('component2', {
    methods: {
     c2method: function(){
       this.$refs.componentOne.c1method();
     }
   }
  });
</script>

如果有人在 Vue.js v3 中尋找解決方案:

https://v3.vuejs.org/guide/migration/events-api.html#event-bus

https://github.com/developit/mitt#install

    import mitt from 'mitt'
    
    const emitter = mitt()
    
    // listen to an event
    emitter.on('foo', e => console.log('foo', e) )
    
    // listen to all events
    emitter.on('*', (type, e) => console.log(type, e) )
    
    // fire an event
    emitter.emit('foo', { a: 'b' })
    
    // clearing all events
    emitter.all.clear()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM