Vue子组件调用父组件的方法

2019-11-28 11:00:35

Vue中子组件调用父组件的方法,这里有三种方法提供参考


下面有三种方法,我自己重点推荐第一种,毕竟这种简单粗暴好用好理解,不过这个有一个弊端,再组件嵌套组件的时候,尤其是用第三方组件里面调用自己的子组件的时候,其实已经是孙子组件了,这个时候就要parent.parent。。。。,这样就不好了,我们就得考虑其他方法了,具体怎么判断是父组件,还是爷爷组件,我会单独出一篇文章讲述。

第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法


父组件
<template>
  <div>
    <child></child>
  </div>
</template>
<script>
  import child from '~/components/dam/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.fatherMethod();
      }
    }
  };
</script>


第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。

父组件

<template>
  <div>
    <child @fatherMethod="fatherMethod"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/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/dam/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {
        console.log('测试');
      }
    }
  };
</script>

子组件

<template>
  <div>
    <button @click="childMethod()">点击</button>
  </div>
</template>
<script>
  export default {
    props: {
      fatherMethod: {
        type: Function,
        default: null
      }
    },
    methods: {
      childMethod() {
        if (this.fatherMethod) {
          this.fatherMethod();
        }
      }
    }
  };
</script>

三种都可以实现子组件调用父组件的方法,但是效率有所不同,根据实际需求选择合适的方法,嗯,就酱~


  • 2020-01-16 08:52:22

    Vue函数式调用组件创建公共组件

    所有组件都需要这么去调用,就会有些许麻烦而且不太美观。像Loading、Toast等这些组件,一页面可以经常用到而且每次显示的内容都可能不一样,这样的话用js的方式【this.$xxx.show(option)】去调用就方便很多,而且代码也更整洁。

  • 2020-01-17 08:37:26

    css transition分别指定多个属性

    transition有四个属性,很多人都会遗忘,分别是transition-property,transition-duration,transition-timing-function,transition-delay,尤其是transition-delay,这个可以实现延迟动画

  • 2020-01-17 08:44:57

    vue keepalive 前进刷新后退不刷新终极解决方案

    另外,我们做路由的时候要有意的根据页面等级做出路由的长度 比如 /a是一级的页面/a/b是二级的页面,下面的文章大家也可以通过判断path的长度来计算rank值,不用有意自定了 这样做的好处有两点,一个就是前进刷新,后退不刷新,还有就是,如果我们做页面进出效果的时候也能排上用场。

  • 2020-01-17 15:28:24

    深入理解vue中的slot与slot-scope

    vue中关于插槽的文档说明很短,语言又写的很凝练,再加上其和methods,data,computed等常用选项使用频率、使用先后上的差别,这就有可能造成初次接触插槽的开发者容易产生“算了吧,回头再学,反正已经可以写基础组件了”,于是就关闭了vue说明文档。