命名特点: 命名时用小驼峰, 在组件标签上用小写-, 在模板中用小驼峰
使用props属性传值的步骤:
1, 在子组件对象中使用props字段声明自定义属性
2, 在子组件标签上绑定属性,传入数据
3,在子组件模板中使用自定义属性绑定和渲染,也可以在对象中监听和计算
注意: 由于单向数据流限制, 不要在子组件中修改props属性值
单向数据流: 组件中的数据只允许由父组件传入子组件, 父组件数据更新时,子组件同步更新, 但是子组件不能直接修改父组件中的数据
<body>
<script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script>
<div id='myApp'>
父组件: {{fatherObj}}
<hr>
<!-- 在子组件标签上绑定自定义属性,传入数据 -->
<my-com child-age="50" :child-obj="fatherObj"></my-com>
</div>
<!-- 组件模板 -->
<template id='myTem'>
<div>
age: {{childAge}} <br>
name: {{childObj.name}} <br>
arr: <i v-for="item in childObj.arr">{{item}}</i>
</div>
</template>
<script>
Vue.component('myCom', {
template: '#myTem',
// props字段用于定义属性, 来接收父组件传值
// 命名特点: 命名时用小驼峰, 在组件标签上用小写-, 在模板中用小驼峰
props: ["childObj", "childAge"],
watch: {
'childObj.age'(newValue, oldValue){
console.log("ageChange")
}
},
created() {
console.log(this.childAge, this.childObj)
// 父组件传入子组件的prop数据是只读的, 不能改, 一改就报错, 如下
// this.childAge = 60;// Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "childAge"
// 单向数据流: 组件中的数据只允许由父组件传入子组件, 父组件数据更新时,子组件同步更新, 但是子组件不能直接修改父组件中的数据
this.childObj.age = 30; // 在不影响内存地址的前提下,不报错,但不建议这样写
this.childObj = {age: 30}; // 报错
},
})
new Vue({
el: '#myApp',
data: {
fatherObj: {
name: "父组件中的数据",
age: 20,
arr: [1,2,3,4,5]
}
},
created() {
setTimeout(() => {
this.fatherObj.age = 30
}, 1000);
},
})
</script>
</body>