目录方式一子组件父组件方式二子组件父组件 注:本文是基于vue3.0的语法 方式一 在script中引入 defineEmit ,import { defineEmit }
注:本文是基于vue3.0的语法
<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>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: vue3.0在子组件中触发的父组件函数方式
本文链接: https://www.lsjlt.com/news/147713.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0