当前位置:首页 > 开发教程 > js/jQuery教程 >

vue3.0在子组件中触发的父组件函数方式

时间:2022-04-29 11:32 来源:未知 作者:钕人如花 收藏

这篇文章主要介绍了vue3.0在子组件中触发的父组件函数方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

注:本文是基于vue3.0的语法

方式一

  • 在script中引入 defineEmit ,import { defineEmit } from 'vue' ;
  • 通过defineEmit定义事件,例如:const emit = defineEmit(['myclick']);
  • 子组件定义了ClickEmit 事件,并且返回了一个函数,在点击事件里通过 emit("myclick") 传递出事件给父组件
  • 在父组件中的 引用的子组件的标签上定义上要传递的事件,具体代码如下

子组件

<template>

 //我派发出了事件,这个事件的命名为myclick,连接至父组件
 <button @click="emit('myclick')">Emit</button>

 //我啥都没派发
 <button>noneEmit</button>

</template>
<script setup>
import { defineEmit } from 'vue' 

// 定义派发事件
const emit = defineEmit(['myclick'])

</script>

父组件

<template>

 //子组件使用通信的 @myclick事件 → 使用父组件函数
 <HelloWorld @myclick="onmyclick"/>

</template>
<script setup>

//导入子组件
import HelloWorld from './components/HelloWorld.vue';

//子组件使用使用父组件函数
const onmyclick = () => {
 console.log(" Come from HelloWorld! ");
}

</script>

方式二

先获取上下文对象,通过该对象的emit()方法进行事件的传出,其他同上

子组件

<template> 
 <button @click="emitclick">emitclick</button>
</template>
<script setup>
import { useContext } from 'vue'

// 获取上下文
const ctx = useContext();
const emitclick = () => {
 ctx.emit('myclick');
}
</script>

父组件

<template>

 //子组件使用通信的 @myclick事件 → 使用父组件函数
 <HelloWorld @myclick="onmyclick"/>
</template>
<script setup>
import HelloWorld from './components/HelloWorld.vue';

const onmyclick = () => {
 console.log(" Come from HelloWorld! ");
}
</script>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持源码搜藏网。


下一篇:没有了

js/jQuery教程阅读排行

最新文章