如何从另一个js文件调用vue组件方法

时间:2017-09-10 19:41:57

标签: javascript ecmascript-6 vue.js vuejs2

我有一个Vue v2.3.4(quasar-framework v0.14.2)模式ComponentA在单击同一组件中的按钮时工作。 MyModal组件似乎工作正常(因为我可以用按钮触发它)。但是我在一个单独的util.js文件中有代码,它应该触发模态(来自'myUtilElement')。我怎么能这样做?

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

2 个答案:

答案 0 :(得分:3)

non parent-child communication on the docs。基本上,您有两个常见选项:事件总线或集中式状态管理 事件总线是一个简单的pub-sub模式:

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

Vue最常见的集中式状态管理库是Vuex,类似于Flux / Redux /等。

Sample image of Vuex data flow

答案 1 :(得分:1)

src / eventBus.js

import Vue from 'vue';
export default new Vue();

src / components / ComponentA.vue

<template>
  <div>
    <div id="lotsofstuff">
      <!-- some code here -->
      <button type="button" class="btn btn-outline-secondary" @click="openModal">Open Modal</button>
    </div>
    <myModal></myModal>
  </div>
</template>

<script>
import MyModal from './MyModal.vue';
import EventBus from '../eventBus';

export default {
  name: 'componentA',

  components: {
    MyModal
  },

  methods: {
    openModal: function () {
      var params = {title: 'My Modal Title'}
      EventBus.$emit('OPEN_MODAL', params)
    },
    // otherMethods:...etc.
}
</script>

src / components / MyModal.vue

<template>
  <div v-show="show">
    <div class="modal-title">{{ title }}</div>
    <!-- some code here -->
  </div>
</template>

<script>
import EventBus from '../eventBus';

export default {
  name: 'MyModal',

  data () {
    return {
      show: false,
      title: 'Default Title'
    }
  },

  created () {
    var self = this;

    EventBus.$on('OPEN_MODAL', function (params) {
      self.show = true;
      self.title = params.title;
    });
  },

  methods: {
    open () {
      this.show = true;
    },

    close () {
      this.show = false;
    }
  }
}
</script>