概述
使用v-model绑定单选框也比较常见,比如性别,要么是男,要么是女。比如单选题,给出多个选择,但是只能选择其中的一个。
在本节课中,我们演示一下这两种常见的用法。
基本用法
我们创建src/components/Demo15.vue,在这个组件中,我们要:
- 1:定义answer响应式变量表示答案
- 2:定义gender变量表示性别
- 3:定义一组单选框,用于选择性别
- 4:定义一组单选框,用于选择答案
- 5:使用两个h3标签,一个用来显示性别,一个用来显示答案
代码如下:
<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/
完整代码
package.json
{
"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"
}
}
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
})
index.html
<!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>
src/main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
src/App.vue
<script setup>
import Demo from "./components/Demo15.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
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>
启动方式
yarn
yarn dev
浏览器访问:http://localhost:5173/