vue实现 页面
Vue 实现页面的基本方法
Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是实现页面的常见方法:
单文件组件(SFC)
使用 .vue 文件组织页面结构,包含模板、脚本和样式三部分。
<template>
<div>
<h1>{{ title }}</h1>
<button @click="handleClick">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
title: 'Vue 页面'
}
},
methods: {
handleClick() {
console.log('按钮被点击')
}
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
路由配置
通过 Vue Router 实现多页面导航,需先安装 vue-router。
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from './views/HomePage.vue'
const routes = [
{ path: '/', component: HomePage }
]
const router = createRouter({
history: createWebHistory(),
routes
})
状态管理
复杂页面可使用 Vuex 或 Pinia 管理全局状态。
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
组件通信
父子组件通过 props 和 emits 交互。
<!-- 父组件 -->
<ChildComponent :msg="message" @update="handleUpdate"/>
<!-- 子组件 -->
<script>
export default {
props: ['msg'],
emits: ['update'],
methods: {
sendUpdate() {
this.$emit('update', newValue)
}
}
}
</script>
生命周期钩子
利用生命周期函数处理特定阶段的逻辑。
export default {
created() {
console.log('组件已创建')
},
mounted() {
console.log('DOM 已挂载')
}
}
API 调用
使用 axios 等库进行数据请求。
import axios from 'axios'
export default {
methods: {
async fetchData() {
const response = await axios.get('/api/data')
this.data = response.data
}
}
}
响应式设计
通过计算属性和侦听器实现动态响应。
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`
}
},
watch: {
firstName(newVal) {
console.log('firstName 变化:', newVal)
}
}
}
注意事项
- 使用
v-if和v-show控制元素显示时需考虑性能差异 - 列表渲染建议始终为
v-for添加:key - 复杂表单可使用
v-model绑定数据 - 样式隔离推荐使用
scoped属性或 CSS Modules
以上方法可根据实际需求组合使用,构建出功能完整的 Vue 页面。







