在 vue 组件上提交表单时如何获取值单选按钮? [英] How can I get value radio button when submit form on the vue component?
问题描述
我有两个组件
我的第一个组件是这样的:
<div>...<form-radio id="gender" name="gender" :data="genderData" v-model="gender">性别</form-radio>...<button type="submit" class="btn btn-primary" @click="submit">提交</button>
</模板><脚本>导出默认{数据() {返回 {性别:空,性别数据:[{id: 1, 标签: 'Men', value:1},{id:2,标签:'女性',价值:2}],}},方法: {提交() {console.log('提交个人资料')console.log(this.gender)}}}
在第一个组件上,它会调用表单输入组件
表单输入组件如下:
<div class="form-group"><label class="col-sm-3 control-label"><slot></slot></label><div class="col-sm-9"><label v-for="数据中的项目" class="radio-inline"><input type="radio" :name="name" :id="item.id" :value="item.value" :required="isRequired ? true : false" @input="$emit('input', $event.target.value)">{{item.label}}标签>
</模板><脚本>导出默认{道具: {名称:字符串,数据:数组,是必须的:{类型:布尔型,默认值:真},模式:字符串,价值: {类型:[字符串,数字]}}}
我使用这样的模式.所以表单输入组件可以在很多组件中使用
但我的问题是:提交按钮时我无法检索值
我是这样试的,但是console.log(this.gender)
的结果是null
我希望在输入数据名称和提交表单时,它会得到性别
我该如何解决这个问题?
对于单选框和选择,使用 @change
而不是 @input
:
I have two component
My first component like this :
<template>
<div>
...
<form-radio id="gender" name="gender" :data="genderData" v-model="gender">Gender</form-radio>
...
<button type="submit" class="btn btn-primary" @click="submit">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
gender: null,
genderData: [
{id: 1, label: 'Men', value:1},
{id: 2, label: 'Women', value:2}
],
}
},
methods: {
submit() {
console.log('submit profile')
console.log(this.gender)
}
}
}
</script>
On the first component, it will call form input component
The form input component like this :
<template>
<div class="form-group">
<label class="col-sm-3 control-label"><slot></slot></label>
<div class="col-sm-9">
<label v-for="item in data" class="radio-inline">
<input type="radio" :name="name" :id="item.id" :value="item.value" :required="isRequired ? true : false" @input="$emit('input', $event.target.value)">
{{item.label}}
</label>
</div>
</div>
</template>
<script>
export default {
props: {
name: String,
data: Array,
isRequired:{
type: Boolean,
default: true
},
pattern: String,
value: {
type: [String, Number]
}
}
}
</script>
I using pattern like that. So the form input component can be used in many components
But my problem here is : I can not retrieve the value when submitting button
I try like that, but the result of console.log(this.gender)
is null
I want when input data name and submit form, it will get the gender
How can I solve this problem?
For radio boxes and selects, use @change
instead of @input
:
<input type="radio" ... @change="$emit('input', $event.target.value)">
这篇关于在 vue 组件上提交表单时如何获取值单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!