简体   繁体   English

孩子与父母之间的 Vue 交流

[英]Vue communcation between child to parent to another child

I got a <payment-child-component> which handles all the subscriptions and payments, i also have我有一个处理所有订阅和付款的<payment-child-component> ,我也有

another <check-active-child-component>另一个<check-active-child-component>

I want these two components to communicate.我想让这两个组件进行通信。 persay in the <payment-component> a user cancel's his subscription i want to fire a method i have in <check-active-component> which called checkActive() persay 在<payment-component>中,用户取消了他的订阅我想触发我在<check-active-component>中调用checkActive()的方法

So from payment-component emits to parent-component when the subscription cancel method is triggered and then fires the checkActive() method inside check-active-component因此,当订阅取消方法被触发时,从payment-component发送到parent-component ,然后在check-active-component中触发checkActive()方法

So if my logic is good, the exact question is: how do i fire a method from parent to child component?所以如果我的逻辑是好的,那么确切的问题是:我如何触发从父组件到子组件的方法?

To call a method of a child component from its parent, you can use ref .要从其父组件调用子组件的方法,您可以使用ref Here is an example:这是一个例子:

Child Component:子组件:

export default {
  name: "ChildComponent",
  methods: {
    childMethod(){
      console.log("hello from child");
    }
  }
};

Parent Component:父组件:

<template>
  <div id="app">
    <ChildComponent ref="myChild"/>
  </div>
</template>

<script>
import ChildComponent from "./components/ChildComponent";

export default {
  name: "App",
  components: {
    ChildComponent
  },
  mounted(){
    this.$refs.myChild.childMethod()
  }
};
</script>

This one is what I am using on my app.这是我在我的应用程序上使用的。

Parent.vue父视图

<template>
    <a @click="run">Click me to execute method from child</a>
</template>
<script>
    export default {
        name:"parent",
        methods: {
            run() {
              this.$root.$refs.child.methodtoexecute();
            }
         }
     }
</script>

Child.vue儿童.vue

<script>
   export default {
     name:"child",
     created() {
        this.$root.$refs.child = this;
     },
     methods: {
        methodtoexecute() {
          alert("hello from child");
        }
     }
   }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM