欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > Vue3 组件通信

Vue3 组件通信

2025/2/25 0:27:05 来源:https://blog.csdn.net/m0_71071209/article/details/140994757  浏览:    关键词:Vue3 组件通信

目录

create-vue创建项目

一. 父子通信

1. 父传子

2. 子传父

 二. 模版引用(通过ref获取实例对象)

1.基本使用

 2.defineExpose

三. 跨层通信 - provide和inject

1. 作用和场景

2. 跨层传递普通数据

3. 跨层传递响应式数据

4. 跨层传递方法


create-vue创建项目

npm init vue@latest

 

一. 父子通信

1. 父传子

  1. 父组件中给子组件绑定属性

  2. 子组件内部通过props选项接收数据

// 父组件
<script setup>
import sonVue from "./son.vue";
</script>
<template><sonVue msg="this is msg" />
</template>
<style scoped></style>
// 子组件
<script setup>
//子组件内部通过props选项接收数据
const props = defineProps({msg: String,
});
</script>
<template><div>{{ msg }}</div>
</template>
<style scoped></style>

2. 子传父

  1. 父组件中给子组件标签通过@绑定事件

  2. 子组件内部通过 emit 方法触发事件

// 父组件
<script setup>
import sonVue from "./son.vue";
// 获取传递子组件传递的值 val
const getMessage = (val) => {console.log(val);
};
</script>
<template><!-- 1.绑定自定义事件 getMessage --><sonVue @getMessage="getMessage" />
</template>
<style scoped></style>
// 子组件
<script setup>
//2. 生成emit方法
const emit = defineEmits(["getMessage"]);const sendMsg = () => {//3.触发自定义事件,并传递参数emit("getMessage", "this is msg");
};
</script>
<template><button @click="sendMsg">测试</button>
</template>
<style scoped></style>

 二. 模版引用(通过ref获取实例对象)

概念:通过 ref标识 获取真实的 dom对象或者组件实例对象

1.基本使用

  1. 调用ref函数生成一个ref对象

  2. 通过ref标识绑定ref对象到标签  

<script setup>
import { ref } from "vue";
//1.调用ref函数得到ref对象
const TestRef = ref(null);//输出得到一个RefImpl对象
console.log(TestRef);
</script><template><!-- 2. 通过ref标识绑定ref对象 --><div ref="TestRef">测试一下</div>
</template>
<style scoped></style>

 2.defineExpose

  • 默认情况下在 <script setup>语法糖下组件内部的属性和方法是不开放给父组件访问的,为了显式暴露某些属性或方法,可以使用 defineExpose
  • 常用于组件上绑定一个ref属性,来获取需要的某些属性或方法
// 子组件
<script setup>
import { ref } from "vue";
//方法
const count = ref(0);
const setCount = () => {count.value++;
};
//值
const a = ref("this is test data");
const b = ref(2);
defineExpose({a,b,setCount,
});
</script><template><button @click="count">count</button>
</template>
<style scoped></style>
//父组件/页面
<script setup>
import TestDefineExpose from "./components/test2/TestDefineExpose.vue"; //引入const onTest = () => {console.log(Exposeref.value.a);console.log(Exposeref.value.b);console.log(Exposeref.value.setCount);
};
</script><template>
<TestDefineExpose ref="Exposeref" /><button @click="onTest"></button>
</template>

三. 跨层通信 - provide和inject

1. 作用和场景

        顶层组件向任意的底层组件传递数据和方法,实现跨层组件通信

2. 跨层传递普通数据

实现步骤

  1. 顶层组件通过 provide 函数提供数据

  2. 底层组件通过 inject 函数提供数据

 

3. 跨层传递响应式数据

在调用provide函数时,第二个参数设置为ref对象

 

4. 跨层传递方法

 顶层组件可以向底层组件传递方法,底层组件调用方法修改顶层组件的数据

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词