Vue3 如何实现组件通信跨组件传递数据。
通过Ref获取子组件数据及调用方法
首先导入子组件,在子组件中定义ref值,这个值要在script中通过ref或reactive来声明一下,然后这个值.value.传递的数据名就是数据。方法同理。
代码:
<template>
<div>
父组件
<My_title ref="arr"></My_title>
<button @click="add">点我ref获取</button>
</div>
</template>
<script setup>
import My_title from './components/my_title.vue'
import { ref, reactive } from 'vue'
// 通过ref来获取子组件数据和方法
// 首先通过ref定义个变量也可以用reactiv定义
const arr = ref(null)
const add = () => {
console.log(arr.value.shuzu);
}
</script>
<template>
<div>
子组件
</div>
</template>
<script setup>
import { ref } from 'vue'
const shuzu = ref([1, 2, 3, 4, 5, 6, 'abc'])
// 通过defineExpose将数据指定抛出 父组件才可以获取需要的数据
defineExpose({
shuzu
})
</script>
实现父子通信
首先在父组件中定义数据,然后通过:将数据通过子组件标签进行传递,子组件中通过defineProps和数据类型来获取父组件。
代码:
<template>
<div>
home
<My_title :arrun="arrun"></My_title>
</div>
</template>
<script setup>
import My_title from './components/my_title.vue'
import { ref, reactive } from 'vue'
// 传递的数据
const arrun = reactive({
title:'张三',
age:18,
sex:'男'
})
</script>
<template>
<div>
title
</div>
</template>
<script setup>
import { ref } from 'vue'
// 通过props来接收
const props = defineProps({
arrun: Object//指定接收的数据类型
})
console.log(props.arrun);
</script>
子传父
首先在子组件定义defineEmits 触发的事件名,父组件通过@来触发方法默认值就是传递的数据。
代码:
<template>
<div>
home
<My_title @add="add"></My_title>
</div>
</template>
<script setup>
import My_title from './components/my_title.vue'
import { ref, reactive } from 'vue'
const add = (v) => {
console.log(v.title);
}
</script>
<template>
<div>
title
<button @click="ONtil">点我传递数据给父组件</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const emit = defineEmits(['add'])
const shuzu = reactive({ title: '123' })
const ONtil = () => {
emit('add', shuzu)
}
</script>
跨组件通信
跨组件通信的实现是,provide传递数据和方法,inject接收数据和方法。import导入后通过属性名,和值传递,接收时通过属性名接收就可以实现跨组件通信。
代码:
<template>
<div>
父组件
<h1>-------------------</h1>
<My_title></My_title>
</div>
</template>
<script setup>
import My_title from './components/my_title.vue'
import { ref, provide, inject, reactive } from 'vue'
const num = ref('父组件的数据');
// provide传递
provide('num', num)
</script>
<template>
<div>
子组件
<br>
{{ num }}
</div>
</template>
<script setup>
import { ref, inject, provide, reactive } from 'vue'
// inject接收
const num = inject('num');
console.log(num);
</script>