利用vue 实现
以下是利用 Vue 实现常见功能的几种方法,分为不同场景和技术要点:
数据绑定与响应式更新
Vue 的核心特性是数据绑定,通过 v-model 实现双向绑定:
<template>
<input v-model="message" placeholder="输入内容">
<p>{{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
条件渲染
使用 v-if 或 v-show 控制元素显示:

<template>
<button @click="toggle">切换显示</button>
<div v-if="isVisible">动态显示的内容</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
},
methods: {
toggle() {
this.isVisible = !this.isVisible
}
}
}
</script>
列表渲染
通过 v-for 渲染数组数据:
<template>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ name: '商品A', price: 100 },
{ name: '商品B', price: 200 }
]
}
}
}
</script>
组件通信
父子组件通过 props 和 $emit 通信:

<!-- 父组件 -->
<template>
<ChildComponent :title="parentTitle" @update="handleUpdate"/>
</template>
<script>
import ChildComponent from './Child.vue'
export default {
components: { ChildComponent },
data() {
return {
parentTitle: '初始标题'
}
},
methods: {
handleUpdate(newTitle) {
this.parentTitle = newTitle
}
}
}
</script>
<!-- 子组件 Child.vue -->
<template>
<div>
<h3>{{ title }}</h3>
<button @click="sendUpdate">更新标题</button>
</div>
</template>
<script>
export default {
props: ['title'],
methods: {
sendUpdate() {
this.$emit('update', '新标题')
}
}
}
</script>
状态管理(Vuex)
对于复杂状态管理,可使用 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++
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
<!-- 组件中使用 -->
<template>
<div>
{{ $store.state.count }}
<button @click="$store.commit('increment')">+1</button>
<button @click="$store.dispatch('incrementAsync')">异步+1</button>
</div>
</template>
生命周期钩子
常用生命周期示例:
<script>
export default {
data() {
return {
timer: null
}
},
created() {
// 组件实例创建后调用
this.fetchData()
},
mounted() {
// DOM挂载后调用
this.timer = setInterval(this.updateClock, 1000)
},
beforeDestroy() {
// 组件销毁前清理
clearInterval(this.timer)
},
methods: {
fetchData() { /* API请求 */ },
updateClock() { /* 更新逻辑 */ }
}
}
</script>
路由管理(Vue Router)
基本路由配置示例:
// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
Vue.use(Router)
export default new Router({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
<!-- App.vue -->
<template>
<div id="app">
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>






