寒假前端学习Day4(Vue)

组件

组件的引入就是需要在<setup>中引入子组件的模块,然后在模板中使用组件。

1
2
3
4
5
6
7
8
<!------App.vue------->
<script setup>
import ChildComp from './ChildComp.vue'
</script>

<template>
<ChildComp />
</template>
1
2
3
4
<!--ChildComp.vue---->
template>
<h2>A Child Component!</h2>
</template>

Props

这是用于父子组件之间通信,父组件将数据传输给子组件然后就可以。

在子组件中定义props

1
2
3
4
5
6
7
8
9
10
<!------ChildComp.vue----->
<script setup>
const props = defineProps({
msg: String
})
</script>

<template>
<h2>{{ msg || 'No props passed yet' }}</h2>
</template>

可以看到在子组件中定义了prop然后再子组件的模板中挂上msg

1
2
3
4
5
6
7
8
9
10
11
<!--App.vue--->
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'

const greeting = ref('')
</script>

<template>
<ChildComp :msg="greeting" />
</template>

所以父组件可以通过greeting传输数据给子组件然后子组件改变msg。


寒假前端学习Day4(Vue)
https://ljw030710.github.io/2024/02/17/寒假前端学习Day4-Vue/
Author
iolzyy
Posted on
February 17, 2024
Licensed under