【问题标题】:how to call a method on the component by clicking Vue.js?如何通过单击 Vue.js 来调用组件上的方法?
【发布时间】:2017-05-11 02:45:00
【问题描述】:

我正在使用 vue-mdl 包中的对话框窗口组件 dialog.vue

<template>
<div class="mdl-dialog-container" v-show="show">
  <div class="mdl-dialog">
    <div class="mdl-dialog__title">{{title}}</div>
    <div class="mdl-dialog__content">
      <slot></slot>
    </div>
    <div class="mdl-dialog__actions" :class="actionsClasses">
      <slot name="actions">
        <mdl-button class="mdl-js-ripple-effect" @click.native.stop="close">Close</mdl-button>
      </slot>
    </div>
  </div>
</div>
</template>

<script>
import mdlButton from './button.vue'
import createFocusTrap from 'focus-trap'

export default {
  components: {
    mdlButton
  },

  computed: {
    actionsClasses () {
      return {
        'mdl-dialog__actions--full-width': this.fullWidth
      }
    }
  },

  data () {
    return {
      show: false
    }
  },

  props: {
    title: {
      type: String
    },
    fullWidth: Boolean
  },

  mounted () {
    this._focusTrap = createFocusTrap(this.$el)
  },

  methods: {
    open () {
      this.show = true
      this.$nextTick(() => this._focusTrap.activate())
      this.$emit('open')
    },
    close () {
      this.show = false
      this._focusTrap.deactivate()
      this.$emit('close')
    }
  }
}
</script>

我想给其他组件带来一个对话窗口

<mdl-dialog></mdl-dialog>
<button class="mdl-button mdl-js-button mdl-button--raised">Click me</button>

我没有找到有关如何在另一个组件中调用一个组件的方法的信息。所有示例主要是使用的道具。告诉我怎么做?

如何在&lt;mdl-dialog&gt;&lt;/mdl-dialog&gt; 中调用方法open()

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    由于他们不是父子,因此您希望使用事件总线。由于您使用的是.vue 文件,因此您可以创建一个名为bus.js 的文件

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

    然后,将其导入您需要发出和侦听集中式事件的任何位置。这是一个简单的例子:

    // SomeComponent.vue
    import bus from './bus.js'
    
    export default {
      methods: {
        log (msg) {
          console.log(msg)
        }
      },
      created () {
        bus.$on('someEvent', this.log)
      }
    }
    

    然后在另一个组件中你可以这样做......

    // AnotherComponent.vue
    import bus from './bus.js'
    
    export default {
      methods: {
        emitClick (msg) {
          bus.$emit('Hello from AnotherComponent.vue')
        },
      },
    }
    

    您可以在这里阅读更多信息:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

    【讨论】:

    • 如何在 mdl-button 中使用总线,如果我通过 npm 拉动它?如果我不在任何地方调用这个方法,为什么还需要一个方法 open()?
    【解决方案2】:

    您可以在父组件的方法中创建以下辅助方法:

    getChild(name) {
        for(let child of this.$children) if (child.$options.name==name) return child;
    },
    

    并以这种方式调用子组件方法:

    this.getChild('mdl-dialog').open();
    

    我没有为 Vue>=2.0 测试它

    【讨论】:

      猜你喜欢
      • 2022-08-13
      • 1970-01-01
      • 2019-06-16
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2022-11-25
      • 2016-06-18
      相关资源
      最近更新 更多