Vue中如何将对象存储为radio输入框的value值?
Vue Radio绑定对象报错的解决方法
原生HTML的radio输入框value属性仅支持字符串或数字类型,直接绑定对象会触发Vue的类型校验错误,提示"Invalid prop: type check failed for prop 'value'. Expected String, Number, got Object"。以下是两种可行的解决方法:
方法一:通过唯一标识映射对象
利用对象的唯一属性(比如示例中的type字段)作为radio的value,选中后再通过该标识从数组中匹配对应的对象。
示例代码:
<template> <div> <input type="radio" v-model="pickType" :value="plan.type" v-for="plan in plans" :key="plan.type" /> </div> </template> <script> export default { data() { return { plans: [{type:'2'},{type:'3'},{type:'1'}], pickType: '' } }, computed: { selectedPlan() { return this.plans.find(plan => plan.type === this.pickType) } } } </script>
方法二:封装自定义Radio组件
通过封装Vue组件,绕过原生radio的value类型限制,直接支持对象作为绑定值。
自定义Radio组件(Radio.vue)
<template> <input type="radio" :name="groupName" :checked="modelValue === value" @change="$emit('update:modelValue', value)" /> </template> <script> export default { props: { groupName: String, value: { type: [String, Number, Object], required: true }, modelValue: { type: [String, Number, Object], required: true } } } </script>
父组件使用
<template> <div> <Radio v-for="plan in plans" :key="plan.type" :group-name="planGroup" :value="plan" v-model="selectedPlan" /> </div> </template> <script> import Radio from './Radio.vue' export default { components: { Radio }, data() { return { plans: [{type:'2'},{type:'3'},{type:'1'}], selectedPlan: null, planGroup: 'plan-selection' } } } </script>
内容的提问来源于stack exchange,提问作者user11302458
相关产品推荐
相关产品推荐

