在 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对应modelValue和update:modelValue事件 -
两者结合能快速构建交互功能

1492

被折叠的 条评论
为什么被折叠?



