简述
父组件通过props传值给子组件
props的使用
直接采用数组
props:['zi_receive_1','zi_receive_2'],
指定类型
props:{
zi_receive_1:Number //指定了接收数据的类型
}
使用对象(更灵活)
props: {
message: {
type: String, //规定的类型
default: '没有传值时的默认值'
},
d1: {
//类型是对象或者数组时,默认值必须是一个函数
type: Array,
default () {
return [1, 7, 5, 4, 6, 40]
}
},
none1: {
type: String,
default: '没有传值时的默认值',
// required:true 必须要传这个
},
d2: {
//类型是对象或者数组时,默认值必须是一个函数
type: Array,
default () {
return [1, 7, 5, 4, 6, 40]
}
}
}
使用
1.在子组件中创建props 作为接收
2.在父组件中注册子组件
3.在父组件使用标签中 使用v-model绑定
理解
刚开始学的小伙伴 可以把 父子组件理解为 大小星球之间的资源运输
子星球(子组件)建造接收器(props)接收器里面得有仓库,仓库得分类,
父星球在进行活动(父组件的使用)大哥阔气顺带照顾小弟 在活动中运输资源
<use_son :son_receive_1="fu_send"></use_son>
然后小弟就可以对资源进行使用(在子组件模板中使用)
一定要理清楚 父组件的传递和子组件中的数据,vue实例也是一个组件
使用_1
父子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<!-- 3 通过:message="message"将data中的数据传递给了props -->
<child-cpn :zi_message='fu_message'></child-cpn>
</div>
</body>
<template id="childCpn">
<div>
显示的信息:{{zi_message}}
</div>
</template>
<script type="text/javascript">
let app=new Vue({
el: '#app',
data: {
fu_message: '我是父组件的内容' //1 Vue实例中的data
},
components: {
'child-cpn': {
template: '#childCpn',
props: ['zi_message'] // 2 组件中的props
}
}
})
</script>
</html>
使用_2
祖父—父子
<body>
<div id="vue">
<use_fu :fu_receive_1="action_grandfather"></use_fu>
</div>
<template id="t1">
<div>
<h2>子组件 </h2>
<h3> 子组件从父组件接受信息:{{son_receive_1}}</h3>
</div>
</template>
<template id="t2">
<div>
<h1>父组件</h1>
<use_son :son_receive_1="action_fu"></use_son>
<h2>父组件从祖父组件接受的信息:{{action_fu}}</h2>
</div>
</template>
<script>
//子构造器
const e1 = {
template: '#t1',
//子组件中的数据
data() {
return {
action_son:'这是子组件的数据'
}
},
props:['son_receive_1','son_receive_2']
}
//父构造器
const e2 = {
//在父组件的构造器中注册子组件
components: {
use_son: e1
},
template: '#t2' ,
// 并在父模板中 使用子组件
//父组件的数据
data() {
return {
action_fu:'父组件的数据',
hobby_fu:[11,22,33,44,55],
props:['fu_receive_1']
}
},
}
const vu = new Vue({
el: '#vue',
data: {
//祖父组件的数据
action_grandfather:'祖父中的数据'
},
//在祖父组件中注册父组件
components: {
use_fu: e2
}
})
</script>
</body>
</html>
<script>
/*
父传子
在子组件中定义 props 放入接收名 用来接受父组件传来的数据
在父组件的使用标签中 使用v-bind绑定数据
:子接受 = 父数据 之后子组件中props中的接收名就有数据
*/
</script>