以下是一个金丹期(Vue 2 + Vuex + Vue Router)的完整代码示例,涵盖状态管理、动态路由、组件通信等核心技能点:
---
### **场景:数据看板系统**
需求:
1. 使用Vuex管理图表数据
2. 动态路由实现权限控制
3. 封装ECharts组件支持主题切换
4. 全局状态管理图表加载状态
---
### **1. Vuex模块化设计(store/modules/dashboard.js)**
```javascript
// 模块化Vuex管理图表状态
const dashboard = {
namespaced: true,
state: {
chartData: null,
isLoading: false,
theme: 'light' // 主题状态
},
mutations: {
SET_CHART_DATA(state, data) {
state.chartData = data
},
SET_LOADING(state, status) {
state.isLoading = status
},
SET_THEME(state, theme) {
state.theme = theme
}
},
actions: {
// 异步获取图表数据
async fetchChartData({ commit }) {
commit('SET_LOADING', true)
try {
const response = await fetch('/api/chart-data')
commit('SET_CHART_DATA', await response.json())
} finally {
commit('SET_LOADING', false)
}
}
},
getters: {
processedData: state => {
// 派生状态处理
return state.chartData ?
state.chartData.map(item => ({
...item,
value: state.theme === 'dark' ? item.value * 1.1 : item.value
})) : []
}
}
}
export default dashboard
```
---
### **2. Vue Router动态路由(router/index.js)**
```javascript
// 动态路由配置
const routes = [
{
path: '/login',
name: 'Login',
component: () => import('@/views/Login.vue')
},
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true }, // 路由元信息
children: [
{
path: 'chart/:type',
name: 'Chart',
component: () => import('@/components/ChartContainer.vue')
}
]
}
]
const router = new VueRouter({
mode: 'history',
routes
})
// 全局路由守卫
router.beforeEach((to, from, next) => {
const isAuthenticated = store.getters['auth/isAuthenticated']
if (to.meta.requiresAuth && !isAuthenticated) {
next({ name: 'Login' })
} else {
next()
}
})
export default router
```
---
### **3. ECharts组件封装(components/ChartContainer.vue)**
```vue
金丹期举例vue代码示例
- 作者:China-Zhejiang-Jiaxing
- 日期:2025年5月13日 11:32
- 浏览:18
加载中...
评论区: