vue实现页面各种案例
Vue 实现页面常见案例
动态表单生成
使用 v-for 和 v-model 动态渲染表单字段,适合问卷或配置类场景。通过数据驱动表单结构,字段类型可扩展为输入框、下拉框等。
<template>
<div v-for="(field, index) in formFields" :key="index">
<label>{{ field.label }}</label>
<input
v-model="field.value"
:type="field.type"
:placeholder="field.placeholder">
</div>
</template>
<script>
export default {
data() {
return {
formFields: [
{ label: '用户名', type: 'text', value: '', placeholder: '输入姓名' },
{ label: '年龄', type: 'number', value: '', placeholder: '输入年龄' }
]
}
}
}
</script>
路由懒加载
通过动态导入拆分代码块,提升首屏加载速度。适用于多页面的 SPA 应用。
const routes = [
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue') // 按需加载
}
]
状态管理(Vuex)
集中管理全局状态,适合跨组件共享数据。包含 state、mutations、actions 和 getters 的完整流程。
// store.js
export default new Vuex.Store({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => commit('increment'), 1000)
}
}
})
自定义指令
实现 DOM 操作逻辑复用,例如自动聚焦输入框。
// main.js
Vue.directive('focus', {
inserted: (el) => el.focus()
})
// 使用方式
<input v-focus>
组件通信
通过 $emit 和 props 实现父子组件数据传递,或使用 provide/inject 跨层级传递。
<!-- 父组件 -->
<child-component :message="parentMsg" @update="handleUpdate"/>
<!-- 子组件 -->
<script>
export default {
props: ['message'],
methods: {
notifyParent() {
this.$emit('update', newValue)
}
}
}
</script>
动画过渡
使用 <transition> 包裹元素,结合 CSS 或 JavaScript 钩子实现动画效果。
<transition name="fade">
<p v-if="show">渐变显示的内容</p>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
服务端渲染(SSR)
通过 nuxt.js 或手动配置实现 SEO 优化。需区分客户端和服务器端的生命周期钩子。
// nuxt.config.js
export default {
modules: ['@nuxtjs/axios'],
axios: { baseURL: 'https://api.example.com' }
}
权限控制
结合路由守卫实现页面访问权限校验,支持角色动态验证。
router.beforeEach((to, from, next) => {
const hasPermission = checkUserRole(to.meta.requiredRole)
hasPermission ? next() : next('/login')
})
图表集成
使用 echarts 或 chart.js 封装可复用的图表组件,通过 watch 响应数据变化。
// 封装 ECharts 组件
export default {
mounted() {
this.initChart()
},
watch: {
chartData: 'updateChart'
},
methods: {
initChart() {
this.chart = echarts.init(this.$el)
}
}
}
国际化
通过 vue-i18n 实现多语言切换,支持动态加载语言包。
// i18n.js
const messages = {
en: { welcome: 'Welcome' },
zh: { welcome: '欢迎' }
}
const i18n = new VueI18n({ locale: 'en', messages })






