用Vue实现
以下是使用 Vue 实现常见功能的几种方法:
数据绑定与响应式更新
使用 v-model 实现双向数据绑定:
<template>
<input v-model="message" placeholder="Edit me">
<p>Message is: {{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
条件渲染
通过 v-if 和 v-show 控制元素显示:

<template>
<p v-if="seen">Now you see me</p>
<p v-show="show">Visible with v-show</p>
</template>
<script>
export default {
data() {
return {
seen: true,
show: true
}
}
}
</script>
列表渲染
使用 v-for 渲染数组:
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.text }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: 'Learn Vue' },
{ id: 2, text: 'Build something' }
]
}
}
}
</script>
事件处理
通过 v-on 或 @ 绑定事件:

<template>
<button @click="counter += 1">Add 1</button>
<p>The button has been clicked {{ counter }} times.</p>
</template>
<script>
export default {
data() {
return {
counter: 0
}
}
}
</script>
组件通信
父组件向子组件传递 props:
<!-- Parent Component -->
<template>
<child-component :message="parentMsg"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: { ChildComponent },
data() {
return {
parentMsg: 'Message from parent'
}
}
}
</script>
<!-- Child Component -->
<template>
<span>{{ message }}</span>
</template>
<script>
export default {
props: ['message']
}
</script>
状态管理
使用 Vuex 进行状态管理:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// Component
<template>
<div>
<p>{{ $store.state.count }}</p>
<button @click="$store.commit('increment')">+</button>
</div>
</template>
生命周期钩子
使用生命周期方法:
export default {
data() {
return {
timer: null
}
},
created() {
this.timer = setInterval(() => {
console.log('Timer tick')
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}
以上示例展示了 Vue 的核心功能实现方式,包括数据绑定、条件渲染、列表渲染、事件处理、组件通信、状态管理和生命周期等常见场景。






