1.嵌套组件
Vue 应用往往是由嵌套组件创建的,例如父组件可以在模板中渲染另一个组件作为子组件。要使用子组件,我们需要先导入它:
import ChildComp from './ChildComp.vue'
//这里的ChildComp是起的别名,随意取
在模板中使用组件:
<ChildComp />
//在父组件中使用的语法
2.Props用法
子组件如果想要从父组件接收动态数据可以通过 props 来实现,首先需要在子组件里面声明props
//child.vue
<script setup>
const props = defineProps({
msg:String,myName:String
//声明数据的方式,变量名:类型
})
<script>
注意 defineProps()
是一个编译时宏,并不需要导入。一旦声明,msg,name等
props 就可以在子组件的模板中使用。
下面是一个父组件向子组件传递动态值的例子:
这个是父组件:
//parent.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const name = ref("my name is LiHua")
const greeting = ref('Hello,China!') //单双引号都可以
</script>
<template>
<ChildComp :msg="greeting"/> <!--通过v-bind语法绑定属性-->
<ChildComp :myName="name"/>
</template>
这个是子组件:
//child.vue
<script setup>
//定义props
const props = defineProps({
msg: String,myName:String
})
</script>
<template>
<h2>{{ msg || myName }}</h2> //msg为空,myName不为空则渲染myName 反之亦然
</template>
这个是渲染后的效果
3.Emits用法
除了接收 props,子组件还可以向父组件触发事件,就会用到Emits,语法如下:
<script setup>
// 声明触发的事件
const emit = defineEmits(['response'])
// 带参数触发
emit('response', 'hello China!')
</script>
emit()
的第一个参数是触发事件的名称,其他所有参数都将传递给事件监听器。父组件可以使用 v-on
监听子组件触发的事件,下面是emit()的例子:
这个是父组件:
//parent.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue' //导入子组件
const childMsg = ref('No child msg yet') //初始化
</script>
<template>
<ChildComp @response="(msg)=>{childMsg=msg}"/>
<h2>{{ childMsg }}</h2>
</template>
这是子组件:
//child.vue
<script setup>
//声明触发的事件
const emit = defineEmits(['response'])
emit('response', 'hello China!') //带参数触发
</script>
<template>
<p>Child component</p>
</template>
这里的处理函数接收了子组件触发事件时的额外参数("hello China!")并将它赋值给了childMsg,进而改变渲染效果。第一张是事件触发前,第二张是事件触发后的效果图对比。
4.插槽用法
除了通过 props 传递数据外,父组件还可以通过插槽将模板片段传递给子组件:
//通过这个语法,这里的ChildComp是给子组件取的别名
<ChildComp>This is some slot content!</ChildComp>
在子组件中,可以使用 <slot>
元素作为插槽出口渲染父组件中的插槽内容(slot content):
<slot>Fallback content</slot>
//通过这个元素来做为插槽的出口
//Fallback content这个是<slot/>在没有任何传递值的时候的默认值
下面是一个利用父组件的 msg
状态来为子组件提供一些插槽内容:
//parent.vue
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const msg = ref('I love chengdu!')
</script>
<template>
<ChildComp>message is : {{msg}}</ChildComp>
</template>
//child.vue
<template>
<slot>Fallback content</slot>
</template>
上面分别是父组件和子组件,下面是结果图: