Vue 3 提供了一系列的内置指令,可以帮助你更方便、高效地开发前端应用。下面我们将介绍几个常用的内置 v-xxx 指令,并提供相应的使用示例。
1. v-model
v-model 指令用于在表单控件或者组件上创建双向数据绑定。
<template>
<input v-model="message" placeholder="编辑我">
<p>消息是: {{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
2. v-if / v-else / v-else-if
这些指令用于条件渲染:根据表达式的真假来渲染元素。
<template>
<div v-if="isVisible">现在你可以看到我</div>
<div v-else>现在你看不到我</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
}
}
</script>
3. v-for
v-for 指令用于渲染列表。
<template>
<ul>
<li v-for="(item, index) in items" :key="index">{{ item }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: ['苹果', '香蕉', '橙子']
}
}
}
</script>
4. v-on
v-on 指令用于监听 DOM 事件。
<template>
<button v-on:click="handleClick">点击我</button>
</template>
<script>
export default {
methods: {
handleClick() {
alert('按钮被点击了!');
}
}
}
</script>
5. v-bind
v-bind 指令用于动态地绑定一个或多个属性,或一个组件 prop 到表达式的返回值。
<template>
<img v-bind:src="imageSrc" alt="Vue logo">
</template>
<script>
export default {
data() {
return {
imageSrc: 'path/to/your/image.jpg'
}
}
}
</script>
希望这份文档能够帮助你更好地理解和使用 Vue 3 的内置指令!