- 第一个参数:props :父组件传递过来的属性会被放到props对象中
- 第二个参数:context:包含3个属性
- attrs:所有的非prop的attribute
- slots:父组件传递过来的插槽(这个在以渲染函数返回时会有作用,后面会讲到)
- emit:当我们组件内部需要发出事件时会用到emit
现创建一个子组件,然后引用子组件
绑定自定义属性
//父组件
<header-list :msg="123" ></header-list>
<script>
import headerList from "../components/headerList.vue";
export default {
components: {headerList },
</script>
在子组件接受,这样父传子就完成了
//子组件
<template>
<div class=''>
<span>{{msg}}</span>
</div>
</template>
<script>
export default {
// 通过props 接收父组件传递过来的数据,模板中可以直接使用
props: ['title'],
setup(props, context) {
// setup函数中要使用的话,要接收一下
console.log(props.title)
}
</script>
在子组件创建一个自定义事件,比如通过点击事件,通过emits发送绑定自定义事件,和需要发送给父组件的数据
//子组件
<template>
<div class=''>
<button @click="send">点击</button>
<span>{{qwe}}</span>
</div>
</template>
<script>
export default {
// 1. 通过第二个参数 context 接收父组件传递过来的方法
setup(props, context) {
const send = () => {
// 通过 context.emit触发父组件的方法,第二个参数为传递的参数,可以传递多个
context.emit('sendData', 100)
context.emit('sendData', 100, 'aaa', 'bbb')
}
// 导出方法提供给模板使用
return {
send
}
}
// 2. 通过第二个参数 解构 emits 接收父组件传递过来的函数
setup(props, { emit }) {
const send = () => {
// 通过emit触发父组件的方法,第二个参数为传递的参数,可以传递多个
emit('sendData', 100)
emit('sendData', 100, 'aaa', 'bbb')
}
return {
send
}
}
}
</script>
在父组件绑定自定义事件,子传父就完成了
//父组件
<template>
<div class="home">
<header-list :qwe="123" @sendData="getData"></header-list>
</div>
</template>
<script>
import headerList from "../components/headerList.vue";
components: {
headerList
}
export default {
components: {
message
}
setup() {
const getData = (msg) => {
//子组件的数据
console.log(msg)
}
// 导出方法提供给模板使用
return {
getData
}
}
</script>
props中不同类型的写法
props: {
// 基础类型指定
propA: Number,
// 指定多个类型
propB: [String, Number],
// 指定必传类型
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default() {
return { mes: 'lihua'}
}
},
// 自定义验证函数
propF: {
validator(value) {
return ['warning', 'success'].includes(value)
}
},
// 具有默认值的函数
prorG: {
type: Function,
default() {
return 'default function'
}
}
}