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元素
链接:https://github.com/mtdream/learningV3
以上是 vue3 父子组件间的传值通信 的全部内容, 来源链接: utcz.com/z/380196.html