1、父组件props传值给子组件。
子组件中定义props字段,类型为Array(如需限制字段值类型,也可以定义为Object的形式)。如下例子,父组件挂载子组件helloWorld,在组件标签上给title赋值,子组件helloWorld定义了props属性,里面有一个值是title,这样子组件就可以使用父组件传递过来的值了。
父组件:home.vue
<template>
<div>
<aaaChildren>
<template #default="scope">
<h1>{{ scope.info.age }}</h1>
</template>
<template #text="scope">
<h2>{{ scope.data }}</h2>
</template>
</aaaChildren>
</div>
</template>
<script>
import aaaChildren from './children/index.vue'
export default {
name:'aaa',
components:{
aaaChildren
}
}
</script>
子组件:hello-world.vue
<template>
<div class="hello">
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
name: "helloWorld",
props:["title"] // 接收传递过来的值
}
</script>
(1)props扩展示例
<template>
<div class="hello">
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
name: "helloWorld",
props: {
title: String, // 限制必须是字符串类型
age: {
type: Number,
default: 0,
required: true,
validator: (value) => {
return value >= 0
}
},
list: {
type: Object,
default: () => ({}) // 引用类型的默认值 必须用一个箭头函数返回
}
}
}
</script>