vue.js 父组件如何触发子组件中的方法

vue.js 父组件如何触发子组件中的方法

子组件:

<template>
  <div>
    child
  </div>
</template>
 
<script>
  export default {
    name: "child",
    props: "someprops",
    methods: {
      parentHandleclick(e) {
        console.log(e)
      }
    }
  }
</script>

父组件:

<template>
  <div>
    <button @click="clickParent">点击</button>
    <child ref="mychild"></child>
  </div>
</template>
 
<script>
  import Child from './child';
  export default {
    name: "parent",
    components: {
      child: Child
    },
    methods: {
      clickParent() {
        this.$refs.mychild.parentHandleclick("嘿嘿嘿");
      }
    }
  }
</script>

注意:

1、在子组件中:

是必须要存在的

2、在父组件中:首先要引入子组件 import Child from ‘./child’;

3、 是在父组件中为子组件添加一个占位,ref="mychild"是子组件在父组件中的名字

4、父组件中 components: {  是声明子组件在父组件中的名字

   5、在父组件的方法中调用子组件的方法,很重要   this.$refs.mychild.parentHandleclick("嘿嘿嘿");

猜你喜欢

转载自blog.csdn.net/weixin_43278947/article/details/85165147