面试题答案
一键面试1. 状态管理方法
通常可以使用 Vuex 或者 React 的 Context API 等状态管理工具。以 Vue 为例,使用 Vuex:
- 定义 state:在 Vuex 的
state
中定义一个变量来存储当前路由信息,例如:
// store.js
const state = {
currentRoute: null
}
- 定义 mutations:用于更新
currentRoute
。
const mutations = {
SET_CURRENT_ROUTE(state, route) {
state.currentRoute = route
}
}
- 定义 actions(可选,如果需要异步操作)。
2. 监听路由变化
- Vue:利用 Vue Router 的导航守卫。
// router.js
import Vue from 'vue'
import Router from 'vue-router'
import store from './store'
Vue.use(Router)
const router = new Router({
routes: [
// 多层嵌套路由配置
{
path: '/home',
name: 'Home',
component: () => import('@/views/Home.vue'),
children: [
{
path: 'product-list',
name: 'ProductList',
component: () => import('@/views/ProductList.vue'),
children: [
{
path: 'product-detail/:id',
name: 'ProductDetail',
component: () => import('@/views/ProductDetail.vue')
}
]
}
]
}
]
})
router.beforeEach((to, from, next) => {
store.commit('SET_CURRENT_ROUTE', to)
next()
})
- React:使用
react-router-dom
中的useLocation
hook。
import { useLocation } from'react-router-dom';
import React, { useEffect } from'react';
import { setCurrentRoute } from './store';
const MyApp = () => {
const location = useLocation();
useEffect(() => {
setCurrentRoute(location);
}, [location]);
return (
// 应用内容
);
}
3. 通过指令更新导航样式和行为
- Vue 自定义指令:
// directives/active-route.js
import Vue from 'vue'
Vue.directive('active-route', {
inserted: function (el, binding, vnode) {
const currentRoute = vnode.context.$store.state.currentRoute;
if (currentRoute && currentRoute.path === binding.value) {
el.classList.add('active');
}
},
componentUpdated: function (el, binding, vnode) {
const currentRoute = vnode.context.$store.state.currentRoute;
if (currentRoute && currentRoute.path === binding.value) {
el.classList.add('active');
} else {
el.classList.remove('active');
}
}
})
在模板中使用:
<ul>
<li v-active-route="'/home'">首页</li>
<li v-active-route="'/home/product-list'">产品列表</li>
<li v-active-route="'/home/product-list/product-detail/1'">产品详情</li>
</ul>
- React 类组件示例:
import React from'react';
import { useSelector } from'react-redux';
const NavItem = ({ path, label }) => {
const currentRoute = useSelector(state => state.currentRoute);
const isActive = currentRoute && currentRoute.path === path;
return (
<li className={isActive? 'active' : ''}>
{label}
</li>
);
}
const Navigation = () => {
return (
<ul>
<NavItem path="/home" label="首页" />
<NavItem path="/home/product-list" label="产品列表" />
<NavItem path="/home/product-list/product-detail/1" label="产品详情" />
</ul>
);
}