vue2中给组件传值props和ref哪一种比较常用?
假设一个经常在不同页面使用的购物车弹窗组件,需要父组件传递默认价格、价格可选范围、数量、可选数量范围、型号、规格等信息,然后购物车组件再将用户选择的数据传回给父组件页面作处理。现在处理方式有2种。
方式1.使用ref,然后在子组件中data函数直接return获得
父组件中
html:
<add-cart-pop
v-on:confirmAddCart="addCart"
ref="addCartPop"
>
</add-cart-pop>
javascript:
this.$refs.addCartPop.$data.name = this.detailData.name;
this.$refs.addCartPop.$data.inventory = this.detailData.inventory;
this.$refs.addCartPop.$data.buttomPrice = this.detailData.buttomPrice;
this.$refs.addCartPop.$data.topPrice = this.detailData.topPrice;
this.$refs.addCartPop.$data.salePrice = this.detailData.salePrice;
this.$refs.addCartPop.$data.quantity = this.detailData.miniPurchaseCount;
this.$refs.addCartPop.$data.unit = this.detailData.unit;
子组件中:
javascript
data(){
return {
name:'',
inventory:0,
quantity:0,
miniPurchaseCount:0,
salePrice:'',
buttomPrice:0,
topPrice:0,
unit:'',
deleteSh:false
}
},
methods: {
addCart() {
this.$emit('confirmAddCart',[this.quantity,this.salePrice]);
}
}
方式2.v-bind绑定,子组件中props接受,return中定义要改变传给父组件的属性:
父组件中:
html:
<add-cart-pop
v-on:confirmAddCart="addCart"
:name="name"
:inventory="inventory"
:quantity="quantity"
:mini-purchase-count="miniPurchaseCount"
:sale-price="salePrice"
:buttom-price="buttomPrice"
:top-price="topPrice"
:unit="unit"
>
</add-cart-pop>
javascript:
this.name = this.detailData.name;
this.inventory = this.detailData.inventory;
this.buttomPrice = this.detailData.buttomPrice;
this.topPrice = this.detailData.topPrice;
this.salePrice = this.detailData.salePrice;
this.miniPurchaseCount = this.detailData.miniPurchaseCount;
this.quantity = this.detailData.miniPurchaseCount;
this.unit = this.detailData.unit
子组件中:
javascript:
props: {
name: {
type:String,
default:''
},
inventory: {
type:Number,
default:0
},
quantity: {
type:Number,
default:0
},
miniPurchaseCount: {
type:Number,
default:0
},
salePrice: {
type:Number,
default:''
},
buttomPrice: {
type:Number,
default:0
},
topPrice: {
type:Number,
default:0
},
unit:{
type:String,
default:''
}
},
data:function () {
return {
cartQuantity:this.quantity,
cartSalePrice:this.salePrice
}
},
methods: {
addCart() {
this.cartQuantity = Number(this.cartQuantity);
this.$emit('confirmAddCart',[this.cartQuantity,this.cartSalePrice]);
}
}
用哪一种是比较好呀
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
props
传递,这也是大部分UI组件使用的方式。你这已经是父子组件了当然是采用props down, events up
。如无必要尽量少的直接操作dom,因为vue的思想
数据驱动视图
,而不是直接操作.当然一些场景下还是有必要使用
$refs
的,比如获取一个元素的宽高..