用vue实现页面编程
Vue 实现页面编程的核心方法
创建 Vue 项目
使用 Vue CLI 或 Vite 快速初始化项目:
npm init vue@latest # Vue 3 推荐
# 或
npm init vite@latest my-vue-app --template vue
组件化开发
单文件组件(.vue)结构示例:
<template>
<div class="example">
<h1>{{ title }}</h1>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue页面示例'
}
},
methods: {
handleClick() {
alert('按钮被点击')
}
}
}
</script>
<style scoped>
.example {
color: #42b983;
}
</style>
路由配置
安装 Vue Router 并配置:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: () => import('../views/About.vue') }
]
const router = createRouter({
history: createWebHistory(),
routes
})
状态管理
使用 Pinia(Vue 官方推荐):
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
组合式 API
Vue 3 推荐写法:

<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
</script>
生命周期应用
常用生命周期钩子示例:
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件已挂载')
// 初始化操作
})
onUnmounted(() => {
console.log('组件已卸载')
// 清理操作
})
表单处理
双向绑定示例:
<template>
<input v-model="message" placeholder="输入内容">
<p>输入的内容是:{{ message }}</p>
</template>
<script setup>
const message = ref('')
</script>
API 请求
使用 axios 示例:

import axios from 'axios'
const fetchData = async () => {
try {
const response = await axios.get('/api/data')
console.log(response.data)
} catch (error) {
console.error('请求出错:', error)
}
}
响应式样式
Vue 3 的样式绑定:
<template>
<div :class="{ active: isActive }" :style="{ color: textColor }">
动态样式
</div>
</template>
<script setup>
const isActive = ref(true)
const textColor = ref('#ff0000')
</script>
自定义指令
创建全局指令:
// main.js
app.directive('focus', {
mounted(el) {
el.focus()
}
})
性能优化
使用 keep-alive 缓存组件:
<template>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</template>






