我需要从复选框绑定对象,在此示例中,复选框是它自己的组件:
<input type="checkbox" :value="option.id" v-model="computedChecked">
这是我的数据并计算出来:
data() {
return {
id: 1,
title: 'test title',
checked: {
'users': {
},
},
}
},
computed: {
computedChecked: {
get () {
return this.checked['users'][what here ??];
},
set (value) {
this.checked['users'][value] = {
'id': this.id,
'title': this.title,
}
}
},
....
上面的示例有些粗糙,但是应该向您展示我要实现的目标:
尽管如此,我似乎还是无法绑定价值。
答案 0 :(得分:1)
我假设您希望computedChecked
像一个数组一样工作,因为如果它是布尔型set
,则在选中/取消选中该复选框时会收到true
/ false
,并且应该很容易处理更改。
当复选框输入的v-model
是一个数组时,Vue希望该数组值与选中状态保持同步,并且在选中/取消选中时,它将为当前选中值分配一个新的数组副本,当:
因此,为了使您的示例正常工作,您需要设置您的设置器,以便每次检查状态更改时,我们都可以从获取器获取最新状态。
这是参考实现:
export default {
name: 'CheckBoxExample',
data () {
return {
id: 1,
title: 'test title',
checked: {
users: {}
}
}
},
computed: {
computedChecked: {
get () {
return Object.getOwnPropertyNames(this.checked.users).filter(p => !/^__/.test(p))
},
set (value) {
let current = Object.getOwnPropertyNames(this.checked.users).filter(p => !/^__/.test(p))
// calculate the difference
let toAdd = []
let toRemove = []
for (let name of value) {
if (current.indexOf(name) < 0) {
toAdd.push(name)
}
}
for (let name of current) {
if (value.indexOf(name) < 0) {
toRemove.push(name)
}
}
for (let name of toRemove) {
var obj = Object.assign({}, this.checked.users)
delete obj[name]
// we need to update users otherwise the getter won't react on the change
this.checked.users = obj
}
for (let name of toAdd) {
// update the users so that getter will react on the change
this.checked.users = Object.assign({}, this.checked.users, {
[name]: {
'id': this.id,
'title': this.title
}
})
}
console.log('current', current, 'value', value, 'add', toAdd, 'remove', toRemove, 'model', this.checked.users)
}
}
}
}