Vue父组件调用子组件方法----多种写法

一、父组件中引入子组件

  • 父组件 parent.vue
<template>
    <div>
    <!-- 调用子组件,子组件的全部内容会显示在这个div中 -->
        <Child/>
    </div>
</template>    

<script setup>
// import 子组件的相对路径
import Child from './child.vue' 
</script>
  • 子组件 child.vue
<template>
    <div>我是子组件</div>
</template>
<script>
</script>

二、父组件中调用子组件的方法

1、export default 写法

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

<script>
import Child from './child';

export default {
    methods: {
        handleClick() {
               this.$refs.child.$emit("childmethod")    //子组件$on中的名字
        },
    },
}
</script>
  • 子组件 child.vue
<template>
    <div>我是子组件</div>
</template>
<script>
export default {
    mounted() {
        this.$nextTick(function() {
            this.$on('childmethods', function() {
                console.log('我是子组件方法');
            });
        });
     },
};
</script>

2、父组件 setup 写法

  • 父组件 parent.vue
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="Child"/>
    </div>
</template>    

<script setup>
import Child from './child';

const Child = ref(null)

function handleClick(){
  Child.value.printfunction();
}


</script>
  • 子组件 child.vue
<template>
    <div>我是子组件</div>
</template>
<script>
export default {
    methods() {
        printfunction(){
          console.log('我是子组件方法');
        }  
     },
};
</script>

3、子父组件都用 setup 写法

  • 父组件 parent.vue
<template>
    <div>
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="Child"/>
    </div>
</template>    

<script setup>
import Child from './child';

const Child = ref(null)

function handleClick(){
  Child.value.printfunction();
}


</script>
  • 子组件 child.vue
<template>
    <div>我是子组件</div>
</template>
<script setup>
  
  function printfunction(){
    console.log('我是子组件方法');
  }  
  
  // 将子组件的方法暴露出去
  defineExpose({
    printfunction
  })
</script>
posted @ 2021-10-03 13:45  落花桂  阅读(6155)  评论(0编辑  收藏  举报
返回顶端
Live2D