2017-09-10 12 views
1

同じコンポーネント内のボタンをクリックすると、Vue v2.3.4(quasar-framework v0.14.2)モーダルComponentAが動作します。 MyModalコンポーネントはうまく動作しているようです(ボタンでトリガーできるので)。しかし私はモーダル( 'myUtilElement'から)を引き起こすべき別のutil.jsファイルにコードを持っています。どうやってやるの?別のjsファイルからvueコンポーネントメソッドを呼び出す方法

ComponentA.vue

<template> 
    <div> 
    <div id='lotsofstuff'></div> 
    <myModal ref="myModal"></myModal> 
    </div> 
</template> 

<script> 
import MyModal from '../MyModal.vue' 

export default { 
    name: 'componentA', 
    components: {MyModal}, 
    methods: { 
    openModal: function() { 
     this.$refs.myModal.open() 
    }, 
    otherMethods:...etc. 
} 

Util.js

import ComponentA from '../ComponentA.vue' 

myUtilElement.addEventListener('click', triggerModal, false) 

function triggerModal() { 
    ComponentA.methods.openModal() 
} 

私は今、コンソールにエラーを以下の取得:

Uncaught TypeError: Cannot read property 'openModal' of undefined 
    at HTMLElement.triggerModal 
+0

new ComponentA? –

+2

[ドキュメントの親子でないコミュニケーション](https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication)を参照してください。 – Nit

+0

''に 'modalTest'という名前を付けている間に' this。$ refs.myModal'を使っているようです。 – Vincent

答えて

2

non parent-child communication on the docsを参照してください。基本的に、イベントバスまたは集中管理の2つの共通オプションがあります。 Vueのため

var bus = new Vue() 
// in component A's method 
bus.$emit('openModal', params) 
// in component B's created hook 
bus.$on('openModal', function(params) { 
    // ... 
}) 

最も一般的な中央集権国家管理ライブラリがVuexで、Reduxのは/ etc /束に似ています。
イベントバスは、単純なパブ・サブパターンです。

Sample image of Vuex data flow

関連する問題