使用v-model绑定单选框也比较常见,比如性别,要么是男,要么是女。比如单选题,给出多个选择,但是只能选择其中的一个。
在本节课中,我们演示一下这两种常见的用法。
我们创建src/components/Demo15.vue,在这个组件中,我们要:
代码如下:
<script setup>
import {ref} from "vue";
const answer = ref("A")
const gender = ref("男")
</script>
<template>
<div>
<h3>性别:{{ gender }}</h3>
<h3>答案:{{ answer }}</h3>
</div>
<div>
<h3>请选择性别</h3>
<input type="radio" v-model="gender" value="男"> 男
<input type="radio" v-model="gender" value="女"> 女
</div>
<div>
<h3>请选择答案</h3>
<input type="radio" v-model="answer" value="A"> A
<input type="radio" v-model="answer" value="B"> B
<input type="radio" v-model="answer" value="C"> C
<input type="radio" v-model="answer" value="D"> D
</div>
</template>
接着,我们修改src/App.vue,引入Demo15.vue并进行渲染:
<script setup>
import Demo from "./components/Demo15.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
然后,我们浏览器访问:http://localhost:5173/
{
"name": "hello",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.3.8"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.5.0",
"vite": "^5.0.0"
}
}
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
<script setup>
import Demo from "./components/Demo15.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
<script setup>
import {ref} from "vue";
const answer = ref("A")
const gender = ref("男")
</script>
<template>
<div>
<h3>性别:{{ gender }}</h3>
<h3>答案:{{ answer }}</h3>
</div>
<div>
<h3>请选择性别</h3>
<input type="radio" v-model="gender" value="男"> 男
<input type="radio" v-model="gender" value="女"> 女
</div>
<div>
<h3>请选择答案</h3>
<input type="radio" v-model="answer" value="A"> A
<input type="radio" v-model="answer" value="B"> B
<input type="radio" v-model="answer" value="C"> C
<input type="radio" v-model="answer" value="D"> D
</div>
</template>
yarn
yarn dev
浏览器访问:http://localhost:5173/