• Vue系列【子组件调用父组件的方法】


    Vue中子组件调用父组件的方法,三种方法

    • 第一种方法是在子组件中通过this.$parent.event来调用父组件的方法(注意:有时候用到第三方框架,需要多套几层$parent)

    父组件:

    <template>
      <div>
        <child></child>
      </div>
    </template>
    <script>
      import child from '~/components/child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethod() {
            console.log('父组件方法');
          }
        }
      };
    </script>

    子组件:

    <template>
      <div>
        <button @click="childMethod()">点击</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            //this.$parent.$parent.fatherMethod();多试几层
            this.$parent.fatherMethod();
          }
        }
      };
    </script>
    • 第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件(Vue推荐使用)。

    父组件:

    <template>
      <div>
        <child @fatherMethod="fatherMethod"></child>
      </div>
    </template>
    <script>
      import child from '~/components/child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethod() {
            console.log('父组件方法');
          }
        }
      };
    </script>

    子组件:

    <template>
      <div>
        <button @click="childMethod()">点击</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            this.$emit('fatherMethod');
          }
        }
      };
    </script>
    • 第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法

    父组件:

    <template>
      <div>
        <child :fatherMethod="fatherMethod"></child>
      </div>
    </template>
    <script>
      import child from '~/components/child';
      export default {
        components: {
          child
        },
        methods: {
          fatherMethod() {
            console.log('父组件方法');
          }
        }
      };
    </script>

    子组件:

    <template>
      <div>
        <button @click="childMethod()">点击</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            if (this.fatherMethod) {
              this.fatherMethod();
            }
          }
        }
      };
    </script>
  • 相关阅读:
    flex 图表使用百分比示例
    flex 图标设置百分比或者其它符号
    大学生求职(打油诗一首)
    flex 图表categoryField设置 labelFunction使用
    如何配置EclipseMe
    google chart图表使用
    Codeforces #Round 632 div2 A~C
    牛客的两道dfs
    约数
    Atcoder ABC162 D RGB Triplets
  • 原文地址:https://www.cnblogs.com/hujunwei/p/16193012.html
Copyright © 2020-2023  润新知