vue3 父子组件间的传值通信
1.父转子
// 父组件
<template>
<div>
<div>
<p>{{ count }}</p>
<Son :countFa="count"/>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import Son from "./son.vue";
const count = ref("我是父组件的值----- 100");
</script>
// 子组件
<template>
<div>
<div>
<div>{{ countFa }}</div>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const count = ref(790);
const props = defineProps({
countFa: String,
})
</script>
2.子传父
// 父组件
<template>
<div>
<div>
<p>{{ count }}</p>
<Son @changeData="changeData"/>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import Son from "./son.vue";
const count = ref("我是父组件的值----- 100");
const changeData = (val) => { console.log(val.value); }
</script>
// 子组件
<template>
<div>
<div>
<div>{{ count }}</div>
<div>
<button @click="getClick">button</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, defineEmits } from "vue";
const count = ref(790);
const emits = defineEmits(["changeData"]); // 声明触发事件 childClick
// 子组件触发父组件方法
const getClick = () => {
count.value++;
emits("changeData", count);
};
</script>
3.父组件调用子组件方法
// 父组件
<template>
<div>
<div>
<p>{{ count }}</p>
<button @click="handleClick">点击调用子组件方法</button>
<Son ref="sonRef" />
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
import Son from "./son.vue";
const count = ref("我是父组件的值----- 100");
const sonRef = ref(null);
const handleClick = () => {
sonRef.value.show(798);
};
</script>
// 子组件
<template>
<div>
<div>
<div>{{ count }}</div>
</div>
</div>
</template>
<script setup>
import { ref, defineExpose } from "vue";
const count = ref(790);
const show = (val) => {
console.log("我是父组件调用子组件的方法", val);
};
defineExpose({
// 这个要加
show,
});
</script>
你可以通过在生命周期钩子前面加上 “on” 来访问组件的生命周期钩子。
下表包含如何在 setup () 内部调用生命周期钩子:
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
模板Refs
通过ref()函数还可以引用页面上的元素或组件
使用步骤:
1、在setup()中创建一个ref对象并返回它
2、在页面上为元素添加ref属性,并设置属性值与创建的ref对象的名称相同
3、当页面渲染完成后,可以通过该ref独享获取到页面中对应的DOM元素
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?