面试题答案
一键面试实现思路
- 配置路由:确保每个tab对应的用户信息板块有独立的路由,这样每个板块可以作为一个独立的组件。
- 使用Keep - Alive:在包裹tab内容的父组件中使用
<keep - alive>
,这样当tab切换时,被切换出去的组件不会被销毁,而是被缓存起来,其状态得以保留。 - 数据请求:在组件的
created
或mounted
钩子函数中进行数据请求。由于组件被缓存,第一次请求后,后续切换回来不会再次触发这些钩子函数,也就避免了重复请求数据。
关键代码
- 路由配置(router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import BasicInfo from '@/components/BasicInfo'
import WorkExperience from '@/components/WorkExperience'
import EducationBackground from '@/components/EducationBackground'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/basicInfo',
name: 'BasicInfo',
component: BasicInfo
},
{
path: '/workExperience',
name: 'WorkExperience',
component: WorkExperience
},
{
path: '/educationBackground',
name: 'EducationBackground',
component: EducationBackground
}
]
})
- 父组件模板(App.vue)
<template>
<div id="app">
<ul>
<li @click="switchTab('basicInfo')">基本信息</li>
<li @click="switchTab('workExperience')">工作经历</li>
<li @click="switchTab('educationBackground')">教育背景</li>
</ul>
<keep - alive>
<router - view :key="$route.path"></router - view>
</keep - alive>
</div>
</template>
<script>
export default {
data() {
return {
currentTab: 'basicInfo'
}
},
methods: {
switchTab(tab) {
this.currentTab = tab
this.$router.push(`/${tab}`)
}
}
}
</script>
- 子组件示例(BasicInfo.vue)
<template>
<div>
<h1>基本信息板块</h1>
<!-- 展示基本信息内容 -->
</div>
</template>
<script>
export default {
data() {
return {
basicInfo: null
}
},
created() {
this.fetchData()
},
methods: {
async fetchData() {
// 模拟数据请求
const response = await axios.get('/api/basicInfo')
this.basicInfo = response.data
}
}
}
</script>
上述代码通过路由配置、Keep - Alive
的使用以及组件的数据请求逻辑,实现了tab切换时保留各板块状态并避免重复请求数据。