vue简单功能实现
Vue 简单功能实现示例
以下是一个基于 Vue 3 的简单计数器功能实现,包含模板、脚本和样式部分:
<template>
<div class="counter">
<h3>当前计数:{{ count }}</h3>
<button @click="increment">增加</button>
<button @click="decrement">减少</button>
<button @click="reset">重置</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
decrement() {
this.count--
},
reset() {
this.count = 0
}
}
}
</script>
<style scoped>
.counter {
text-align: center;
margin: 20px;
}
button {
margin: 0 5px;
padding: 8px 16px;
cursor: pointer;
}
</style>
待办事项列表实现
这是一个简单的待办事项列表功能:
<template>
<div>
<input v-model="newTodo" @keyup.enter="addTodo" placeholder="添加新任务">
<ul>
<li v-for="(todo, index) in todos" :key="index">
{{ todo.text }}
<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({ text: this.newTodo })
this.newTodo = ''
}
},
removeTodo(index) {
this.todos.splice(index, 1)
}
}
}
</script>
表单双向绑定示例
实现一个简单的用户注册表单:
<template>
<form @submit.prevent="submitForm">
<div>
<label>用户名:</label>
<input v-model="form.username" type="text">
</div>
<div>
<label>密码:</label>
<input v-model="form.password" type="password">
</div>
<div>
<label>邮箱:</label>
<input v-model="form.email" type="email">
</div>
<button type="submit">注册</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
username: '',
password: '',
email: ''
}
}
},
methods: {
submitForm() {
console.log('提交的表单数据:', this.form)
// 这里可以添加表单验证和提交逻辑
}
}
}
</script>
条件渲染示例
根据条件显示不同内容的实现:
<template>
<div>
<button @click="toggleShow">切换显示</button>
<p v-if="show">现在你看到我了</p>
<p v-else>现在你看不到我了</p>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
},
methods: {
toggleShow() {
this.show = !this.show
}
}
}
</script>
计算属性示例
使用计算属性实现一个简单的购物车总价计算:
<template>
<div>
<div v-for="(item, index) in cart" :key="index">
{{ item.name }} - ¥{{ item.price }} × {{ item.quantity }}
</div>
<h3>总价:¥{{ totalPrice }}</h3>
</div>
</template>
<script>
export default {
data() {
return {
cart: [
{ name: '商品A', price: 100, quantity: 2 },
{ name: '商品B', price: 200, quantity: 1 },
{ name: '商品C', price: 50, quantity: 3 }
]
}
},
computed: {
totalPrice() {
return this.cart.reduce((total, item) => {
return total + (item.price * item.quantity)
}, 0)
}
}
}
</script>
这些示例涵盖了 Vue 的核心功能,包括数据绑定、事件处理、条件渲染、列表渲染和计算属性等基本概念。







