报错1:
[Vue warn]: Error in v-on handler: “TypeError: “name” is read-only”
methods: {
del(idx) {
this.list.splice(idx, 1)
},
add() {
const { good, list } = this
// 1.判断
const { name, price } = good
if (name == '') return
if (price == '') return
// 2.组装一条资产
const id = list.length > 0 ? list[list.length - 1].id + 1 : 1
const obj = {
id,
name,
price,
time: new Date(),
}
// 3.添加到list中
list.push(obj)
// 4.清空内容
name = ''
price = ''
},
},
错误原因:
const { name, price } = good解构赋值是将good.name的值赋值给name变量,后面的清空内容清空的是变量name的值而非good.name的值,变量name的值无法清空,故报错read-only
正确写法:
<script>
export default {
data() {
return {
good: {
name: '', // 名称
price: 0, // 价格
},
list: [
{ id: 100, name: '外套', price: 199, time: new Date('2010-08-12') },
{ id: 101, name: '裤子', price: 34, time: new Date('2013-09-01') },
{ id: 102, name: '鞋', price: 25.4, time: new Date('2018-11-22') },
{ id: 103, name: '头发', price: 19900, time: new Date('2020-12-12') },
],
}
},
methods: {
del(idx) {
this.list.splice(idx, 1)
},
add() {
const { good, list } = this
// 1.判断
if (good.name == '') return
if (good.price == '') return
// 2.组装一条资产
const id = list.length > 0 ? list[list.length - 1].id + 1 : 1
const obj = {
id,
name: good.name,
price: good.price,
time: new Date(),
}
// 3.添加到list中
list.push(obj)
// 4.清空内容
good.name = ''
good.price = ''
},
}
}
</script>
报错2:
错误原因: v-modul双向绑定了sum
计算属性也是变量, 如果想要直接赋值, 需要使用完整写法=>开启读写模式
解决办法:
computed: {
"属性名": {
set(值){
},
get() {
return "值"
}
}
}