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>

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


  • 2018-10-20 20:44:03

    RecycleView4种定位滚动方式演示

    将RecyclerView滑动到指定位置,或者检索RecyclerView的某一项(各个项的高度不确定),然后定位滚动这到一项,将它显示。 下面就讲解4种RecyclerView定位滚动

  • 2018-10-21 22:29:24

    android ScollView 嵌套 WebView 底部空白,高度无法自适应解决

    最近要做一个页面,需要 ScrollView 嵌套 WebView,怎么嵌套,怎么解决焦点和 touch 事件冲突,网上一大堆,这里就不赘述了,但是发现 WebView 从一个高度很高的网页加载一个高度很低的网页的时候,高度无法自适应了,造成底部会有一大片的空白,解决方案找到了挺多,描述一下:

  • 2018-10-24 15:24:54

    getcachedir和getexternalcachedir的区别

    应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的。 大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中。 这样当该应用被卸载后,这些数据还保留在SDCard中,留下了垃圾数据。 如果你想让你的应用被卸载后,与该应用相关的数据也清除掉,该怎么办呢?

  • 2018-10-25 11:05:16

    SimpleDateFormat转换时间,12,24时间格式

    在使用SimpleDateFormat时格式化时间的 yyyy.MM.dd 为年月日而如果希望格式化时间为12小时制的,则使用hh:mm:ss 如果希望格式化时间为24小时制的,则使用HH:mm:ss