vue3的一些知识记录
创建时间:2025-04-16 15:43
长度:1130
浏览:0
评论: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>