props: [] - 只声明变量, 不能类型校验
props: {} - 声明变量和校验类型规则 - 不对则报错
父组件定义属性
子组件接收父组件传的值
props: {
backgroundColor: String, // 外部传入此变量的值必须为字符串类型,否则报错
title: {
type: String,
required: true // 必须传入此变量的值,否则会报错
},
textColor: {
default: '#fff', // 约束 textColor 的默认值,如果不传递值,则为默认值
type: String // textColor 的值的类型必须是字符串类型
}
}
当父组件向子组件传递了一个商品对象时
[
{
"goods_id": 1,
"goods_name": "低帮城市休闲户外鞋天然牛皮COOLMAX纤维",
"goods_price": 128,
"goods_count": 2,
"goods_img": "https://yanxuan-item.nosdn.127.net/3a56a913e687dc2279473e325ea770a9.jpg",
"goods_state": true
},
{
"goods_id": 2,
"goods_name": "网易味央黑猪猪肘330g*1袋",
"goods_price": 39,
"goods_count": 10,
"goods_img": "https://yanxuan-item.nosdn.127.net/d0a56474a8443cf6abd5afc539aa2476.jpg",
"goods_state": true
},
{
"goods_id": 3,
"goods_name": "KENROLL男女简洁多彩一片式室外拖",
"goods_price": 128,
"goods_count": 2,
"goods_img": "https://yanxuan-item.nosdn.127.net/eb1556fcc59e2fd98d9b0bc201dd4409.jpg",
"goods_state": false
},
{
"goods_id": 4,
"goods_name": "21春季新品,儿童时尚圆领卫衣1-8岁",
"goods_price": 85,
"goods_count": 4,
"goods_img": "https://yanxuan-item.nosdn.127.net/fa21cced568eb41f9b0be3a098bd3f31.jpg",
"goods_state": false
},
{
"goods_id": 5,
"goods_name": "去皮去刺,辅食好选择,比目鱼纯肉250g",
"goods_price": 43,
"goods_count": 1,
"goods_img": "https://yanxuan-item.nosdn.127.net/011f3c5062a6318187be711ca4214cb1.jpg",
"goods_state": false
}
]
此时,子组件中需要使用 v-model 对父组件传递过来的数组中的每一个商品信息的goods_state 与子组件复选框进行双向绑定,但是属性值 props 是只读属性,不可修改,会报错。
解决方案:
在子组件中本地 data 中定义一个变量用于接收父组件传递过来的属性值,之后使用 data 中定义的变量进行 v-model 双向绑定。因为传递过来的是一个对象,good 和 localGood 指向同一片内存空间,所以在 data 中 localGood 里的 goods_state 改变也会导致传递过来的 good 中的 goods_state 进行改变。
侦听器,侦听新值和旧值的变化,所以 handler 函数中的形参为 newVal 和 oldVal
watch: {
goodItem: {
deep: true,
immediate: true,
handler (newVal, oldVal) {
this.good.goods_count = newVal.goods_count
}
}
}
computed: {
isAll: {
// 设置一个值, 需要接受一个值,接收的值为 v-model 双向绑定的值
set (isChecked) {
console.log(isChecked)
this.goodsList.forEach(item => {
item.goods_state = isChecked
})
},
// 获取值,需要返回一个值,返回的值为 是否选中 的值
// every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。
get () {
return this.goodsList.every(item => {
return item.goods_state === true
})
}
}
computed: {
num () {
return this.goodsList.reduce((prev, item) => {
// prev 累计值
if (item.goods_state) {
prev += item.goods_count
}
return prev
}, 0)
},
allPrice () {
return this.goodsList.reduce((prev, item) => {
if (item.goods_state) {
prev += item.goods_count * item.goods_price
}
return prev
}, 0)
}
}