vue实现小功能
Vue.js 是一个渐进式 JavaScript 框架,适合实现各种小型功能。以下是几个常见小功能的实现方法:
计数器功能
通过 Vue 的响应式数据绑定实现简单的计数器:
<template>
<div>
<p>当前计数:{{ count }}</p>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
}
</script>
待办事项列表
实现一个简单的待办事项管理功能:
<template>
<div>
<input v-model="newTodo" @keyup.enter="addTodo">
<ul>
<li v-for="(todo, index) in todos" :key="index">
{{ todo }}
<button @click="removeTodo(index)">删除</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newTodo: '',
todos: []
}
},
methods: {
addTodo() {
if(this.newTodo.trim()) {
this.todos.push(this.newTodo)
this.newTodo = ''
}
},
removeTodo(index) {
this.todos.splice(index, 1)
}
}
}
</script>
图片切换器
实现图片轮播功能:
<template>
<div>
<img :src="currentImage" alt="轮播图片">
<button @click="prevImage">上一张</button>
<button @click="nextImage">下一张</button>
</div>
</template>
<script>
export default {
data() {
return {
images: [
'image1.jpg',
'image2.jpg',
'image3.jpg'
],
currentIndex: 0
}
},
computed: {
currentImage() {
return this.images[this.currentIndex]
}
},
methods: {
nextImage() {
this.currentIndex = (this.currentIndex + 1) % this.images.length
},
prevImage() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length
}
}
}
</script>
表单验证
实现简单的表单验证功能:
<template>
<div>
<form @submit.prevent="submitForm">
<input v-model="email" type="email" placeholder="邮箱">
<span v-if="!isEmailValid">请输入有效的邮箱地址</span>
<input v-model="password" type="password" placeholder="密码">
<span v-if="!isPasswordValid">密码长度至少6位</span>
<button type="submit" :disabled="!isFormValid">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
email: '',
password: ''
}
},
computed: {
isEmailValid() {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email)
},
isPasswordValid() {
return this.password.length >= 6
},
isFormValid() {
return this.isEmailValid && this.isPasswordValid
}
},
methods: {
submitForm() {
alert('表单提交成功')
}
}
}
</script>
这些示例展示了 Vue 实现常见小功能的基本方法,可以根据具体需求进行调整和扩展。Vue 的响应式特性和组件化设计使得开发小型功能变得简单高效。







