一、父传子
父子关系更多是指使用关系
因为在单文件组件中不能通过components来创建结构上的子组件
意味着在项目中,所谓父组件和子组件都是单独的单文件组件,它们更多是的引入使用关系
父传子就是将父组件中的数据传递给子组件
二、四个步骤实现父传子数据传递
步骤一:准备好父组件需要传递的数据
步骤二:实现父传子:在父组件中使用子组件的位置,
为子组件的props成员赋值
步骤三:接收父组件传递过来的数据成员
步骤四:渲染效果
实际传递只需要2、3步骤
父组件代码
.<template>
<div class="father">
<h1>我是父组件</h1>
<!-- 使用 -->
<!-- 步骤二:实现父传子:在父组件中使用子组件的位置,
为子组件的props成员赋值 -->
<!-- 1.如果需要变量,则需要用到v-bind动态绑定,缩写 -->
<son1 :getname="name"></son1>
<!-- 2.如果赋值是一个字符串,就直接赋值,输出结果是:name -->
<!-- <son1 getname="name"></son1> -->
</div>
</template>
<script>
//引入组件
import son1 from "./son1";
export default {
//注册
components: {
son1,
},
data() {
return {
// 步骤一:准备好父组件需要传递的数据
name: "山竹",
};
},
};
</script>
.<style lang="less" scoped>
.father {
//添加样式区分
width: 100%;
background-color: cadetblue;
}
</style>
子组件代码
.<template>
<div class="son">
<h1>我是子组件</h1>
<!-- 步骤四:渲染效果 -->
<h2>接收到父组件传递过来的name值:{{ getname }}</h2>
</div>
</template>
<script>
export default {
// 步骤三:接收父组件传递过来的数据成员
// 方法一:
// props: ["getname"],
// 方法二:
props: {
// 这种写法支持对props成员进行配置
getname: {
type: String, //要求传递的类型,大写开头
required: true, //强制传递,否则报错
default: "山竹回家了", //不传值时默认传
},
},
data() {
return {
// getname: "?",
};
},
};
</script>
.<style lang="less" scoped>
.son {
//添加样式区分
width: 80%;
background-color: cornflowerblue;
}
</style>
效果
三、父传子传递原理
四、常见报错问题
Property or method “getname” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
一般是没设置
props
接受父元素数据,直接渲染了
The data property “getname” is already declared as a prop. Use prop default value instead.
一般是props
成员与data
重复
Missing required prop: “getname”
没有为必要属性传递数据.(可以看下步骤二是不是忘了传)
Invalid prop: type check failed for prop “getname”. Expected String with value “111”, got Number with value 111.
无效的数据传递,这里需要字符串,但接收到了数字.(看下接收和发布的数据类型)