【问题标题】:Call great grand children component method调用曾孙组件方法
【发布时间】:2017-08-10 12:43:59
【问题描述】:

我在 Vue 2.2.1 中得到了一组嵌套组件如下:

<Root>
  <VForm>
    <Accordion>
      <Panel>
        <Stripe ref="stripe">

并且我需要在提交表单时调用 Stripe 组件上的方法getToken。在我的 &lt;VForm&gt; 组件上,我有以下模板。

<template>
  <form :method="method" :action="action" :class="classes" :autocomplete="autocomplete" @submit.prevent="submit">
    <slot></slot>
  </form>
</template>

<script>

  export default {

    props: {
      method: {
        type: String,
        default: 'POST'
      },
      action: {
        required: true,
        type: String
      },
      classes: {
        type: String
      },
      autocomplete: {
        type: String,
        default: 'on'
      }
    },

    methods: {
      submit(){
        this.$refs.stripe.getToken
      }
    }
  }

</script>

但我得到Uncaught TypeError: Cannot read property 'getToken' of undefined。我还通过在&lt;v-form&gt; 级别发出事件来尝试它,但如果我没记错的话,我的理解是事件从孩子流向父母,所以这不起作用。

如何在&lt;v-form&gt; 提交时触发stripe.getToken

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    你可以使用公共汽车。

    const bus = new Vue();
    
    Vue.component("parent", {
        methods:{
            triggerStripe(){
                bus.$emit('get-token');
            }
        }
    })
    
    Vue.component("stripe",{
        mounted(){
            bus.$on('get-token', () => this.getToken());
        }
    })
    

    【讨论】:

    • 谢谢,这行得通,但我必须在窗口对象window.bus = new Vue(); 上定义总线以使其全局可访问,否则条带组件将无法接收总线实例。
    • @enriqg9 没错,当使用单个文件组件时,你会这样做:)
    猜你喜欢
    • 2019-10-16
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多