VUE框架CLI组件化在父组件中获取子组件------VUE框架
原创
©著作权归作者所有:来自51CTO博客作者旧约Alatus的原创作品,请联系作者获取转载授权,否则将追究法律责任
<template>
<div>
<h1 ref="hehe">{{msg}}</h1>
<!-- 在App这个父组件中传数据给子组件去接收 -->
<!-- 实现数据动态 -->
<Car brand="宝马520" color="白色" v-bind:price="10" ref="car1"></Car>
<hr>
<Car brand="比亚迪汉" color="银色" v-bind:price="10" ref="car2"></Car>
<hr>
<Car brand="奔驰E" color="黑色" v-bind:price="10" ref="car3"></Car>
<hr>
<button @click="printCarInfo()">打印汽车信息</button>
</div>
</template>
<script>
import Car from './components/Car.vue'
export default {
methods : {
printCarInfo(){
// 获取子组件,可以获取当前这个组件下所有的组件,哪怕它不是组件是HTML标签也会被获取
console.log(this.$refs.car1.brand);
console.log(this.$refs.car1.color);
console.log(this.$refs.car1.price);
console.log(this.$refs.car2.brand);
console.log(this.$refs.car2.color);
console.log(this.$refs.car2.price);
console.log(this.$refs.car3.brand);
console.log(this.$refs.car3.color);
console.log(this.$refs.car3.price);
// 这个也可以用来获取页面上的HTML元素
// 只要我们为它打上了ref标签即可
console.log(this.$refs.hehe.innerText);
}
},
name : "App",
data(){
return {
msg : "汽车信息"
}
},
components : {Car}
}
</script>
<style>
</style>
<template>
<div>
<h3>品牌:{{brand}}</h3>
<h3>价格:{{cprice}}</h3>
<h3>颜色:{{color}}</h3>
<!-- 不要去修改prop里面的数据 -->
<button @click="add()">按一下加1</button>
</div>
</template>
<script>
export default {
name : "Car",
data(){
return {
cprice : this.price
}
},
methods : {
add(){
this.cprice++;
}
},
// data(){
// return {
// brand : '宝马520',
// price : 10,
// color : "黑色"
// }
// }
// 简单的接收方式,直接用数组接受
// props : ['brand','color','price']
// 第二种,添加上类型限制的格式
// props : {
// brand : String,
// price : Number,
// color : String
// }
// 第三种,添加类型限制,并且还可以添加默认值,还可以添加必要性
props : {
brand : {
type : String,
required : true
},
color : {
type : String,
required : true
},
price : {
type : Number,
required : true,
default : 0
}
}
}
</script>
<style>
</style>