0%

组件间传值

昨天写到一半,婶婶就打电话过来让我去东站接她,急急忙忙关了电脑今天才发现我之前写的都没保存,啊啊啊啊啊!!!我不想重写了,就这样吧,粗略总结一下。

父子之间传值我就不想写了,比较不熟悉的是父孙之间的传值。

父传孙

在父组件文件中,有子组件,在这个子组件中传入一个属性,然后在子组件文件中,用一个孙组件,在这个孙组件中用v-bind= “$attr”直接实现透传,最后在孙组件文件中,通过props的形式去获取。

孙传父

整体思路和子传夫比较像,都是通过触发点击事件传值的。首先,孙组件触发父组件的函数将想要传递过去的值传过去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//孙组件文件GrandSon.vue
<template>
<div>
<h1>我是孙组件</h1>
<button @click="sendToFather">点我传值</button>
</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const hello = ref('okok')
const emit = defineEmits(['sendToFather'])
const sendToFather = () => {
emit('sendToFather', hello.value)
}
</script>

<style scoped lang="scss">
div {
margin: 10px 0;
}
</style>

作为中间组件的子组件,用v-bind=”$attrs” 做中间管道,在vue2中孙传父是用v-on=“$listeners”作为中间管道,但是在vue3中废除了这个语法,改成不管是孙传父,还是父传孙,子组件都用v-bind=”$attrs” 做透传。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//子组件 Son.vue
<template>
<div>
<h1>我是子组件</h1>
<GrandSon v-bind="$attrs" />
</div>
</template>

<script setup lang="ts">
import GrandSon from './GrandSon.vue'
</script>

<style scoped lang="scss">
div {
margin: 10px 0;
}
</style>

父组件用函数属性接受

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<div>
<h1>我是父组件</h1>
<Son @sendToFather="sendToFather" />
<div>子组件传过来的值{{ hello }}</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import Son from './Son.vue'
const hello = ref('')
const sendToFather = (val: string) => {
hello.value = val
console.log(val, '子组件传过来的值')
}
</script>
<style scoped></style>