父子组件
父子组件传递数据,子组件向父组件传递数据使用defineEmits,父组件向子组件传递数据使用变量的形式。
父组件向子组件传递数据
父组件传递
vue
<script setup>
import Child from './Child'
import {ref} from 'vue'
const parentMsg=ref('父组件传递值是a')
</script>
<template>
<div class="hello">
<!-- 父组件通过:变量(这里是info)绑定值 -->
<Child :info="parentMsg"></Child>
</div>
</template>
<style scoped>
</style>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
子组件接收
vue
<script setup>
import { toRefs, defineProps } from 'vue'
const props = defineProps({
info: String, //子组件接收父组件传递过来的值
itemData: { //子组件接收父组件传递过来的值
type: Object,
default: () => ({})
}
})
//使用父组件传递过来的值
const {info} =toRefs(props)
</script>
<template>
<!-- info是父组件传递过了的值 -->
<div>子组件拿到了父组件的值是{{info}}</div>
</template>
<style scoped>
</style>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
子组件向父组件传递数据 defineEmits
子组件传递
vue
<script setup>
import { defineEmits } from 'vue'
// 使用defineEmits创建名称,接受一个数组
const emit = defineEmits(['clickChild'])
const clickChild=()=>{
let param={
content:'b'
}
//传递给父组件
emit('clickChild',param)
}
</script>
<template>
<button @click="clickChild">点击子组件</button>
</template>
<style scoped>
</style>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
父组件接收
vue
<script setup>
import Child from './Child'
import {ref} from 'vue'
const result=ref('')
const clickEven=(val)=>{
console.log(val);
result.value=val.content
}
</script>
<template>
<div>
<!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->
<Child @clickChild="clickEven"></Child>
<p>子组件传递的值是 {{result}}</p>
</div>
</template>
<style scoped>
</style>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20