黄朝忆的个人博客
登录|注册

vue3的一些知识记录

创建 2025-04-16 15:43113072 浏览0 评论

自定义事件

   组件定义事件: /components/com-header/com-header.vue

   一种是用$emit, 一种是用defineEvents函数

<template>
	<view>
		hello {{username}}, age = {{age}}, defineProps.demoAttr={{demoAttr}}
		<button @click="$emit('add', 123)">按钮</button>
		<button @click="send">自定义事件1</button>
	</view>
</template>

<script setup>
	const emits = defineEmits(['onSend']);
	function send () {
		emits('onSend', Math.random())
	} 
</script>

<style>

</style>


   调用事件

<com-header
	@add="onAdd"
	@onSend="(num) => console.log(num)"
></com-header>



组件内部爆漏属性、方法给父组件使用

   组件 /components/com-values/com-values.vue

<template>
	<view>
		com-values组件的count: {{ count }}
		<button @click="() => updateCount(20)">33</button>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	const count = ref(100);
	
	function updateCount (num = 1){
		console.log(num, 'num')
		count.value +=num;
	}
	
	defineExpose({
		count,
		updateCount
	})
</script>


   调用


<template>
	<view>
		<com-values ref="child"></com-values>
		<button @click="update">修改子值</button>
	</view>
</template>

<script setup>
	import { onMounted, ref } from 'vue';
	const child = ref(null);
	
	const update = () => {
		child.value.updateCount(2);
	}
</script>



评论(共 0 条)

编辑器加载中...
vue3的一些知识记录 - uni-app学习笔记