vue页面实现
Vue 页面实现基础步骤
安装 Vue.js 项目脚手架
使用 Vue CLI 或 Vite 创建项目,运行命令 npm init vue@latest 或 npm create vite@latest,根据提示选择 Vue 模板。
创建单文件组件
在 src/components 目录下新建 .vue 文件,例如 MyComponent.vue,包含 <template>、<script> 和 <style> 三个部分:
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue!'
}
}
}
</script>
<style scoped>
div {
color: blue;
}
</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: '/', component: Home },
{ path: '/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')
状态管理
使用 Pinia(推荐)
安装:npm install pinia,创建 src/stores/counter.js:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
在组件中使用:
<script setup>
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
</script>
<template>
<button @click="store.increment">{{ store.count }}</button>
</template>
生命周期与 API 调用
组合式 API 示例
使用 ref 和 onMounted:

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
const data = ref(null)
onMounted(async () => {
const response = await axios.get('https://api.example.com/data')
data.value = response.data
})
</script>
响应式样式
Scoped CSS 与 CSS 变量
在组件中使用 scoped 样式防止污染:
<style scoped>
.button {
--primary-color: #42b983;
background-color: var(--primary-color);
}
</style>
组件通信
父子组件传值
父组件传递 props:
<template>
<ChildComponent :title="pageTitle" />
</template>
<script setup>
const pageTitle = 'Vue 3 Demo'
</script>
子组件接收:
<script setup>
defineProps(['title'])
</script>
<template>
<h2>{{ title }}</h2>
</template>






