Home  >  Article  >  Web Front-end  >  How to call the method of child component in vue parent component

How to call the method of child component in vue parent component

青灯夜游
青灯夜游Original
2021-10-26 14:28:20121225browse

Calling method: 1. In the parent component, directly call the child component's method through ref; 2. In the parent component, call through the component's "$emit" and "$on" methods.

How to call the method of child component in vue parent component

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

How to directly call the child component in the parent component in the Vue project:

Option 1: Directly call the child through ref Component method;

//父组件中

<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/>
    </div>
</template>    

<script>
import Child from &#39;./child&#39;;

export default {
    methods: {
        handleClick() {
              this.$refs.child.sing();
        },
    },
}
</script>


//子组件中

<template>
  <div>我是子组件</div>
</template>
<script>
export default {
  methods: {
    sing() {
      console.log(&#39;我是子组件的方法&#39;);
    },
  },
};
</script>

Option 2: Through the $emit and $on methods of the component;

//父组件中

<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child"/>
    </div>
</template>    

<script>
import Child from &#39;./child&#39;;

export default {
    methods: {
        handleClick() {
               this.$refs.child.$emit("childmethod")    //子组件$on中的名字
        },
    },
}
</script>

//子组件中

<template>
    <div>我是子组件</div>
</template>
<script>
export default {
    mounted() {
        this.$nextTick(function() {
            this.$on(&#39;childmethods&#39;, function() {
                console.log(&#39;我是子组件方法&#39;);
            });
        });
     },
};
</script>

Related recommendations: "vue.js Tutorial

The above is the detailed content of How to call the method of child component in vue parent component. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn