发布日期:2025-02-01 12:08 点击次数:179
在 Vue 3 中,v-model 是用于完了表单位素双向绑定的辅导。关于单选框(radio),v-model 不错将选中的值与 Vue 组件的数据绑定起来。以下是 v-model 与单选框量度使用的详备理会和示例。
1.基本用法
单选框频频用于让用户从多个选项中采选一个值。使用 v-model 不错将选中的值与 Vue 组件的数据绑定。
示例代码
<template>
<div>
<p>请采选一个选项:</p>
<label>
<input chk=1&type="radio" v-model="selectedOption" value="option1" />
选项 1
</label>
<label>
<input chk=1&type="radio" v-model="selectedOption" value="option2" />
选项 2
</label>
<label>
<input chk=1&type="radio" v-model="selectedOption" value="option3" />
选项 3
</label>
<p>你采选的是:{{ selectedOption }}</p>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
// 界说反映式数据
const selectedOption = ref('');
return {
selectedOption,
};
},
};
</script>
代码理会
v-model 绑定:
v-model 绑定到 selectedOption,用于存储用户采选的值。每个单选框的 value 属性默示该选项的值。
反映式数据:
使用 ref 界说 selectedOption,它是一个反映式数据,运行值为空字符串 ''。
显露采选效果:
通过 {{ selectedOption }} 动态显露用户采选的值。
2.动态生成单选框
要是选项是动态的(举例从 API 赢得),不错使用 v-for 动态生成单选框。
示例代码
<template>
<div>
<p>请采选一个选项:</p>
<label v-for="option in options" :key="option.value">
<input chk=1&type="radio" v-model="selectedOption" :value="option.value" />
{{ option.label }}
</label>
<p>你采选的是:{{ selectedOption }}</p>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
// 界说反映式数据
const selectedOption = ref('');
// 动态选项
const options = [
{ value: 'option1', label: '选项 1' },
{ value: 'option2', label: '选项 2' },
{ value: 'option3', label: '选项 3' },
];
return {
selectedOption,
options,
};
},
};
</script>
3.绑定对象
要是需要将单选框的值绑定到一个对象的属性,不错使用 v-model 绑定到对象的属性。
示例代码
<template>
<div>
<p>请采选一个选项:</p>
<label>
<input chk=1&type="radio" v-model="form.selectedOption" value="option1" />
选项 1
</label>
<label>
<input chk=1&type="radio" v-model="form.selectedOption" value="option2" />
选项 2
</label>
<label>
<input chk=1&type="radio" v-model="form.selectedOption" value="option3" />
选项 3
</label>
<p>你采选的是:{{ form.selectedOption }}</p>
</div>
</template>
<script>
import { reactive } from 'vue';
export default {
setup() {
// 界说反映式对象
const form = reactive({
selectedOption: '',
});
return {
form,
};
},
};
</script>
追想
使用 v-model 不错松驰完了单选框的双向绑定。单选框的值通过 value 属性开导。不错量度 v-for 动态生成单选框。要是需要绑定到对象的属性,不错使用 reactive 或 ref 界说反映式对象。
通过以上当作,不错在 Vue 3 中高效地使用 v-model 惩处单选框的逻辑。
看到这里的一又友温暖一下小编呗足球投注app,创作不易,温暖就是饱读吹!