背景:父组件传递值给子组件是指,如何把在父组件页面中的数据传递给写在当前父组件页面的子组件页面中
知识点
1.在子组件的页面中使用props,声明好准备要传过来的字段
2.在父组件页面中的子组件标签上写要传递过来的字段和值,并且要与在子组件声明的字段名一致
3.父组件传递非props属性值,是通过$attrs对象传递的
实战例子:
父组件
<template>
<!-- <child-message title="我是标题" content="我是内容"></child-message>-->
<child-message class="abc" :title="title" :content="content"></child-message>
</template>
<script>
import ChildMessage from "./ChildMessage";
export default {
name: "ParentTest",
components: {ChildMessage},
data(){
return{
title: "我是标题",
content: "我是内容"
}
}
}
</script>
<style scoped>
</style>
子组件
<template>
<div>
<!-- 非prop的Attribute传递值使用$attrs对象, title和content是父组件传递过来的 -->
<h2 :class="$attrs.class">{{title}}</h2>
<p>{{content}}</p>
</div>
</template>
<script>
export default {
name: "ChildMessage",
//传递过程中props起到关键作用,主要是用于声明好父组件传过来的字段与在子组件页面中能对应上
//注意props的书写方式有很多种
// props:['title','content'],数组形式
props:{
//对象形式
// title: String,
// content: String
title:{
type: String,
required: true
},
content:{
type: String,
required: true
}
},
data(){
return{
}
}
}
</script>
<style scoped>
</style>