v-model用于实现双向数据绑定,使用v-model绑定输入框是Vue3中最常见的用法之一。
比如,在制作登录界面的时候,我们会使用v-model绑定用户名和密码,这里的用户名和密码都是输入框。
我们创建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>
接着,我们修改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>
{
"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/Demo14.vue"
</script>
<template>
<h1>欢迎跟着Python私教一起学习Vue3入门课程</h1>
<hr>
<Demo/>
</template>
<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/