概述
v-model用于实现双向数据绑定,使用v-model绑定输入框是Vue3中最常见的用法之一。
比如,在制作登录界面的时候,我们会使用v-model绑定用户名和密码,这里的用户名和密码都是输入框。
基本用法
我们创建src/components/Demo14.vue,在这个组件中,我们要:
- 1:使用ref定义username和password两个动态响应的字符串
- 2:创建一个文本输入框和一个密码输入框
- 3:给文本输入框通过v-model绑定username,给密码输入框通过v-model绑定password
- 4:添加一个登录按钮
- 5:给登录按钮绑定一个onLogin事件
- 6:实现onLogin方法,在这个方法中组织表单的默认行为,并打印用户名和密码
代码如下:
<script setup>
import {ref} from "vue";const username = ref("")
const password = ref("")function onLogin(){console.log("用户名:",username.value)console.log("密码:",password.value)
}
</script>
<template><form v-on:submit.prevent><div>账号:<input type="text" v-model="username"></div><div>密码:<input type="password" v-model="password"></div><div><button @click="onLogin">登录</button></div></form>
</template>
接着,我们修改src/App.vue,引入Demo14.vue并进行渲染:
<script setup>
import Demo from "./components/Demo14.vue"
</script>
<template><h1>欢迎跟着Python私教一起学习Vue3入门课程</h1><hr><Demo/>
</template>
然后,我们浏览器访问:http://localhost:5173/
代码分析
先看看完整代码:
<script setup>
import {ref} from "vue";const username = ref("")
const password = ref("")function onLogin(){console.log("用户名:",username.value)console.log("密码:",password.value)
}
</script>
<template><form v-on:submit.prevent><div>账号:<input type="text" v-model="username"></div><div>密码:<input type="password" v-model="password"></div><div><button @click="onLogin">登录</button></div></form>
</template>
关键技术1:通过<form v-on:submit.prevent>
,我们利用Vue3的特性,阻止了表单的默认提交事件。
<form v-on:submit.prevent>
关键技术2:通过<button @click="onLogin">登录</button>
,我们给表单设置了提交事件
<button @click="onLogin">登录</button>
完整代码
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/Demo14.vue"
</script>
<template><h1>欢迎跟着Python私教一起学习Vue3入门课程</h1><hr><Demo/>
</template>
src/components/Demo14.vue
<script setup>
import {ref} from "vue";const username = ref("")
const password = ref("")function onLogin(){console.log("用户名:",username.value)console.log("密码:",password.value)
}
</script>
<template><form v-on:submit.prevent><div>账号:<input type="text" v-model="username"></div><div>密码:<input type="password" v-model="password"></div><div><button @click="onLogin">登录</button></div></form>
</template>
启动方式
yarn
yarn dev
浏览器访问:http://localhost:5173/