Vue
1. 创建Vue3项目结构,包含组件、响应式数据、事件处理、生命周期等核心功能
2. 实现计数器功能展示数据绑定
3. 添加条件渲染和列表渲染示例
4. 包含计算属性和样式绑定
5. 添加子组件演示组件通信
<!-- App.vue -->
<template>
<div class="container">
<h1>{{ title }}</h1>
<p>计数器: {{ count }}</p>
<button @click="increment">增加</button>
<div v-if="showMessage" class="message">
{{ message }}
</div>
<button @click="toggleMessage">
{{ showMessage ? '隐藏信息' : '显示信息' }}
</button>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} - 价格: {{ formatPrice(item.price) }}
</li>
</ul>
<child-component
:total="count"
@reset="handleReset"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const title = 'Vue3示例'
const count = ref(0)
const showMessage = ref(true)
const message = '欢迎使用Vue3!'
const items = ref([
{ id: 1, name: '商品A', price: 100 },
{ id: 2, name: '商品B', price: 200 }
])
const formattedCount = computed(() => `当前计数: ${count.value}`)
function increment() {
count.value++
}
function toggleMessage() {
showMessage.value = !showMessage.value
}
function formatPrice(price) {
return `¥${price.toFixed(2)}`
}
function handleReset() {
count.value = 0
}
onMounted(() => {
console.log('组件已挂载')
})
</script>
<style scoped>
.container {
max-width: 800px;
margin: 20px auto;
padding: 20px;
}
button {
margin: 5px;
padding: 8px 15px;
background: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.message {
padding: 10px;
background: #f0f0f0;
margin: 10px 0;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 8px;
margin: 5px 0;
background: #f8f8f8;
}
</style>
<!-- ChildComponent.vue -->
<template>
<div class="child">
<h3>子组件</h3>
<p>接收的计数: {{ total }}</p>
<button @click="resetCounter">重置计数器</button>
</div>
</template>
<script setup>
defineProps({
total: Number
})
const emit = defineEmits(['reset'])
function resetCounter() {
emit('reset')
}
</script>
<style scoped>
.child {
margin-top: 20px;
padding: 15px;
border: 1px solid #eee;
}
</style>
运行前需安装依赖:npm install vue@3
。包含以下功能:
1. 响应式数据管理(ref/computed)
2. 事件处理和方法调用
3. 条件渲染(v-if)和列表渲染(v-for)
4. 组件通信(props/emits)
5. 生命周期钩子(onMounted)
6. 样式绑定和CSS作用域
7. 计算属性格式化显示