用vue实现页面编程
使用 Vue 实现页面开发
初始化 Vue 项目
使用 Vue CLI 或 Vite 创建新项目:
npm create vue@latest my-vue-app
cd my-vue-app
npm install
npm run dev
组件化开发
在 src/components 目录下创建 .vue 文件,例如 HelloWorld.vue:
<template>
<div>
<h1>{{ message }}</h1>
<button @click="changeMessage">修改文本</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "Hello Vue!"
};
},
methods: {
changeMessage() {
this.message = "文本已更新";
}
}
};
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
路由配置
安装 vue-router 并配置路由:
npm install vue-router
在 src/router/index.js 中定义路由:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
在 main.js 中引入路由:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
状态管理(Vuex/Pinia)
使用 Pinia(推荐):
npm install pinia
在 src/stores/counter.js 中定义 Store:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
在组件中使用 Store:
<script setup>
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
</script>
<template>
<button @click="counter.increment">{{ counter.count }}</button>
</template>
数据请求(Axios)
安装 Axios 并封装请求:
npm install axios
在 src/api/index.js 中封装请求:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
export const fetchData = () => instance.get('/data');
在组件中调用:
<script>
import { fetchData } from '@/api';
export default {
data() {
return {
data: null
};
},
async created() {
this.data = await fetchData();
}
};
</script>
响应式样式
使用 scoped 样式隔离组件样式,或结合 CSS 预处理器(如 SCSS):
<style scoped lang="scss">
$primary-color: #42b983;
h1 {
color: $primary-color;
}
</style>
构建与部署
运行构建命令生成生产环境代码:
npm run build
部署生成的 dist 目录到服务器(如 Nginx、Netlify 等)。
以上步骤涵盖了 Vue 页面开发的核心流程,包括组件化、路由、状态管理、数据请求和样式处理。







