这篇文章主要讲解了“vue3组件通信方式有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue3组件通信方式有哪些”吧!
面试题经常会问到vue3组件间的通信方式,下文列举了七种常见的通信方式。
props
emit
v-model
refs
provide/inject
eventBus
Vuex4/pinia(vuex5)
父组件以数据绑定的形式声明要传递的数据,子组件通过defineProperty()方法创建props对象,即可拿到父组件传来的数据。
父组件的template中:
<!-- list是我们要传递的数据 -->
<child-components :list="list"></child-components>
子组件:
<template>
<ul>
<li v-for="i in props.list" :key="i">{{ i }}</li>
</ul>
</template>
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
list: {
type: Array,
default: () => [],
},
})
</script>
注意在
emit
方式也是Vue中最常见的组件通信方式,该方式用于子传父;
父组件的template中:
<!-- add是子组件要传递的动作,handleAdd是监听到之后执行的事件 -->
<child-components @add="handleAdd"></child-components>
<script>
const list = ref([1,2,3])
const handleAdd = value => {
list.value.push(value)
}
</script>
子组件中:
const emits = defineEmits(['add'])
emits('add', 1)
v-model不能严格成为数据的传递方式,其实只是减少了代码量。
<ChildComponent v-model:list="list" />
// 等价于
<ChildComponent :list="pageTitle" @update:list="list = $event" />
子组件需要emit一个叫update:xxx的事件,再把需要更新的响应式数据传给emit方法的第二个参数即可,如:
const emits = defineEmits(['update:list'])
emits('update:list', arr)
有时候想访问 r e f s 绑 定 的 组 件 的 属 性 或 者 方 法 , 我 们 会 使 用 refs绑定的组件的属性或者方法,我们会使用 refs绑定的组件的属性或者方法,我们会使用refs。但是Vue3不同于Vue2,在 Vue3的setup中我们是无法访问到this的,所以我们需要借助一个方法,那就是getCurrentInstance,该方法返回了当前的实例对象。
父组件如下:
<template>
<div>
<Child ref="child"></Child>
<button @click="show">Show Child Message</button>
</div>
</template>
<script setup>
import { getCurrentInstance } from '@vue/runtime-core';
import Child from './Child.vue';
const currentInstance = getCurrentInstance()
function show() {
currentInstance.$refs.child.alertMessage()
}
</script>
子组件代码如下:
<template>
<div>
<h2>{{ message }}</h2>
</div>
</template>
<script setup>
import { ref } from '@vue/reactivity';
let message = ref('我是子元素').value
const alertMessage = function () {
alert(message)
}
defineExpose({
message,
alertMessage
})
</script>
注意⚠️,通过<script setup>
语法糖的写法,其组件是默认关闭的,也就是说如果是通过$refs
或者$parents
来访问子组件中定义的值是拿不到的,必须通过defineExpose向外暴露你想获取的值才行。
provide/inject是 Vue 中提供的一对 API。无论层级多深,API 都可以实现父组件到子孙组件的数据传递。
// 父组件中
provide('list', list.value)
// 子组件中
const list = inject('list')
Vue 3 中移除了 eventBus,但可以借助第三方工具来完成。Vue 官方推荐使用 mitt 或 tiny-emitter。
Vuex 和 Pinia 是 Vue 3 中的状态管理工具,使用这两个工具可以轻松实现组件通信。
感谢各位的阅读,以上就是“vue3组件通信方式有哪些”的内容了,经过本文的学习后,相信大家对vue3组件通信方式有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。