Vue3 表单与事件交互:v-model 和 @click 的完全解读

在 Vue3 中,几乎所有交互都是通过**事件绑定**和**双向数据绑定**实现的。

`@click`(或 `v-on:click`) → **监听用户动作**
`v-model` → **实现数据与界面同步**

 一、@click:事件绑定

基本用法

<template>
  <button @click="handleClick">点我</button>
</template>

<script setup>
function handleClick() {
  alert('你点击了按钮!')
}
</script>

传参

<template>
  <button @click="addCount(5)">加 5</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
function addCount(num) {
  count.value += num
}
</script>

事件修饰符

  • .prevent:阻止默认行为

  • .stop:阻止事件冒泡

  • .once:只触发一次

<form @submit.prevent="submitForm">
  <button type="submit">提交</button>
</form>

二、v-model:双向绑定

v-model 会自动将表单输入值与数据变量绑定。

输入框

<template>
  <input v-model="name" placeholder="请输入姓名" />
  <p>你好,{{ name }}</p>
</template>

<script setup>
import { ref } from 'vue'
const name = ref('')
</script>

复选框

<template>
  <input type="checkbox" v-model="checked" /> 我已阅读
  <p>状态:{{ checked }}</p>
</template>

<script setup>
const checked = ref(false)
</script>

多选框(绑定数组)

<template>
  <label><input type="checkbox" value="Vue" v-model="skills" /> Vue</label>
  <label><input type="checkbox" value="React" v-model="skills" /> React</label>
  <p>已选:{{ skills }}</p>
</template>

<script setup>
const skills = ref([])
</script>

下拉框

<template>
  <select v-model="city">
    <option value="bj">北京</option>
    <option value="sh">上海</option>
  </select>
  <p>选择了:{{ city }}</p>
</template>

<script setup>
const city = ref('bj')
</script>

三、自定义组件的 v-model

在子组件中,v-model 会默认绑定到 modelValue prop,并通过 update:modelValue 事件更新。

子组件:MyInput.vue
<template>
  <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" />
</template>

<script setup>
defineProps(['modelValue'])
</script>
父组件使用
<MyInput v-model="username" />
<p>{{ username }}</p>

<script setup>
import { ref } from 'vue'
import MyInput from './MyInput.vue'
const username = ref('')
</script>

四、@click 与 v-model 搭配示例

<template>
  <input v-model="count" type="number" />
  <button @click="count++">+1</button>
  <button @click="count--">-1</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

小结

  • @click 用于监听用户行为,可配合修饰符简化操作

  • v-model 实现表单与数据的双向绑定

  • 在自定义组件中,v-model 对应 modelValueupdate:modelValue 事件

  • 两者结合能快速构建交互功能

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值