父子组件传值在radio单选中的相关错误问题
目的
封装一个简单的从数据库读取字典的组通过select或radio渲染
父组件
// 当type是select时没任何问题,radio不行,具体问题写在了下面代码的注释里,报错如下截图
<DictSelect dictTypeCode="sys_common_status" type="radio" :value.sync="formFieldsData.status"/>
报错
子组件
<template>
<div>
<!--类型是select时没任何问题-->
<el-select v-if="type === 'select'" :value="value" filterable :placeholder="placeholder" @change="onChange">
<el-option
v-for="item in dictOptions"
:key="item.value"
:label="item.label"
:value="+item.value">
</el-option>
</el-select>
<!--类型是radio时,如果用 :value="value"会导致完全无法切换单选值,换成v-model="value"后可以切换,但是报错,报错信息如上面截图-->
<el-radio-group v-if="type === 'radio'" v-model="value" @change="onChange">
<el-radio
v-for="item in dictOptions"
:key="item.value"
:label="Number(item.value)"
>{{item.label}}</el-radio>
</el-radio-group>
</div>
</template>
<script>
import { getDict } from '@/utils/dictionary'
export default {
name: 'DictSelect',
data() {
return {
// 字典数据
dictOptions: []
}
},
props: {
type: {
type: String,
default: 'select'
},
value: {
type: Number
},
dictTypeCode: {
type: String,
required: true
},
placeholder: {
type: String,
default: ''
}
},
created() {
console.log(this.value)
this.getDict(this.dictTypeCode)
},
methods: {
// 获取所属区域字典
async getDict(type) {
const dicts = await getDict(type)
this.dictOptions = dicts
return dicts
},
onChange(value) {
console.log(value)
this.$emit('update:value', value)
}
}
}
</script>
<style scoped>
</style>
不能直接用 v-model 绑定一个 prop 吧,可以考虑用 :value,然后配合 onchange 去 emit 更新,或者 v-model 不用绑定 prop,而是绑定 data 中的属性,然后通过 emit('update:value') 一样可以更新父组件的属性。