准备工作
创建两个组件 src/components/Parent.vue 和 src/components/Child.vue,其中Parent.vue是Child.vue的父级组件
将Parent.vue在App.vue中注入,将Child.vue在Parent.vue中注入
App.vue:
<!--html代码(模块展示 显示在页面上的内容)-->
<template>
<Parent />
</template>
<!--vue代码-->
<script >
import Parent from "./components/Parent.vue";
export default {
components:{
Parent
}
}
</script>
Parent.vue:
<template>
<h2>Parent</h2>
<Child />
</template>
<script>
import Child from "./Child.vue";
export default {
data(){
return{
}
},
components:{
Child
}
}
</script>
Child.vue:
<template>
<h2>Child</h2>
</template>
<script>
export default {
data(){
return{
}
}
}
</script>
具体实现
props可传递不同类型的值
Parent.vue:
<template>
<h2>Parent</h2>
<div>
<Child :msg="msg" :age="age" :names="names" :userInfo="userInfo"/>
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
data(){
return{
msg:"通过父级传给子级的信息", // 传递字符串 String
age:20, // 传递数字 Number
names:["Jack","Jan","John"], //传递数组 Array
userInfo:{ // 传递对象 Object
name:"May",
age: 22
}
}
},
components:{
Child
}
}
</script>
通过v-bind绑定数据,将值传递给子级组件使用
Child.vue:
<template>
<h2>Child</h2>
<p>父级传来的字符串:{{ msg }}</p>
<p>父级传来的数字:{{ age }}</p>
<p>父级传来的数组:</p>
<ur>
<li v-for="(item,index) in names" :key="index">{{ item }}</li>
</ur>
<p>父级传来的对象:</p>
<p>{{ userInfo.name }}</p>
<p>{{ userInfo.age }}</p>
</template>
<script>
export default {
data(){
return{
}
},
// 接收父级传来的数据
props:["msg","age","names","userInfo"]
}
</script>
props的校验--type
props传递默认值--default
注:对于String和Number类型的值,可以直接使用default,而对于数组和对象,必须采用函数的方法进行返回
props的必传项--required
当父级未给子级传递子级所想要的必传项时,控制台将会抛出警告,而页面不会出现任何异常
注:
props对父级传来的值仅可读,不可对其传来的值进行修改