概念
v-bind
和 v-on
是 Vue 中两个非常常用的指令,分别用于属性绑定和事件绑定。
v-bind
v-bind
用于动态地绑定属性。你可以使用 v-bind
来绑定 HTML 元素的各种属性,例如 class
、style
、href
等。在 Vue 3 中,你还可以使用简写语法 :
来代替 v-bind
。
1. 基本用法
<template>
<div>
<!-- 使用 :class 绑定 class 属性 -->
<div :class="{ 'active': isActive, 'error': hasError }">Example</div>
<!-- 使用 :style 绑定 style 属性 -->
<div :style="{ color: textColor, fontSize: `${textSize}px` }">Styled Text</div>
<!-- 使用 :href 绑定 href 属性 -->
<a :href="url">Link</a>
</div>
</template>
<script setup>
import { ref } from 'vue';
// 使用 ref 创建响应式变量
const isActive = ref(true);
const hasError = ref(false);
const textColor = ref('red');
const textSize = ref(16);
const url = ref('https://www.example.com');
</script>
2. 动态属性绑定
<template>
<div>
<!-- 使用计算属性绑定动态 class -->
<div v-bind:class="computedClasses">Dynamic Classes</div>
<!-- 直接在插值表达式中使用 JavaScript 表达式 -->
<div :style="{ color: isActive ? 'green' : 'red' }">Dynamic Style</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const isActive = ref(true);
const computedClasses = () => {
return {
active: isActive.value,
'text-danger': !isActive.value
};
};
</script>
内联样式绑定数组、对象
通过 :style 将这个对象应用到元素上。当 dynamicStylesObject 中的属性值发生变化时,元素的样式也会相应地更新。
<template>
<div>
<!-- 内联样式绑定对象 -->
<div :style="dynamicStylesObject">Dynamic Styles (Object)</div>
</div>
</template>
<script setup>
import { reactive } from 'vue'
const dynamicStylesObject = reactive({
color: 'blue',
fontSize: '20px',
backgroundColor: 'lightgray'
})
</script>
通过绑定一个数组到 v-bind:style 或 :style 上,可以将多个样式对象组合应用到元素上。baseStyles 和 dynamicStylesArray 是两个样式对象,通过 :style 将它们组合应用到元素上。这种方式可以用于将基本样式与动态样式组合,实现更灵活的样式管理。以下是例子:
<template>
<div>
<!-- 内联样式绑定数组 -->
<div :style="[baseStyles, dynamicStylesArray]">Dynamic Styles (Array)</div>
</div>
</template>
<script setup>
import { reactive } from 'vue'
const baseStyles = reactive({
color: 'green',
fontSize: '18px'
});
const dynamicStylesArray = reactive({
backgroundColor: 'yellow'
});
</script>
v-on
v-on
用于监听 DOM 事件,例如点击、输入、鼠标移入等。你可以使用 v-on
来绑定事件处理函数。在 Vue 3 中,你还可以使用简写语法 @
来代替 v-on
。
1. 基本用法
<template>
<div>
<!-- 使用 v-on 绑定 click 事件 -->
<button v-on:click="handleClick">Click me</button>
<!-- 使用 @ 绑定 mouseover 事件 -->
<div @mouseover="handleMouseOver">Mouse over me</div>
</div>
</template>
<script setup>
const handleClick = () => {
console.log('Button clicked');
};
const handleMouseOver = () => {
console.log('Mouse over');
}
</script>
2. 事件修饰符和参数
在事件处理函数中,可以使用 $event
获取原生事件对象。Vue 3 提供了一些事件修饰符,用于简化事件处理逻辑。
<template>
<div>
<!-- 传递事件参数 -->
<input v-on:input="handleInput($event)" />
<!-- 使用修饰符.prevent 阻止默认行为 -->
<form v-on:submit.prevent="handleSubmit">Submit Form</form>
<!-- 使用修饰符.stop 阻止事件冒泡 -->
<div v-on:click.stop="handleClick">Click me</div>
</div>
</template>
<script setup>
const handleInput = (event) => {
console.log('Input value:', event.target.value);
};
const handleSubmit = () => {
console.log('Form submitted');
};
const handleClick = () => {
console.log('Div clicked');
}
</script>