MST

星途 面试题库

面试题:Vue Router在中等规模电商项目中的页面导航应用

在一个中等规模的电商Vue项目中,有商品列表页、商品详情页、购物车页和个人中心页。请描述如何使用Vue Router实现这些页面之间的导航,并确保用户在刷新页面时,路由状态能正确恢复。同时说明如何处理路由参数传递商品ID到商品详情页的操作。
36.7万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. Vue Router 配置
    • 首先在项目中安装并引入 Vue Router。在 router/index.js 文件中进行配置。
    • 定义路由数组 routes
import Vue from 'vue';
import Router from 'vue-router';
import GoodsList from '@/views/GoodsList.vue';
import GoodsDetail from '@/views/GoodsDetail.vue';
import Cart from '@/views/Cart.vue';
import PersonalCenter from '@/views/PersonalCenter.vue';

Vue.use(Router);

export default new Router({
  mode: 'history', // 使用 history 模式,使 URL 更美观,并且刷新页面时能正确处理路由
  routes: [
    {
      path: '/goodsList',
      name: 'GoodsList',
      component: GoodsList
    },
    {
      path: '/goodsDetail/:id', // 使用动态路由参数 :id 传递商品ID
      name: 'GoodsDetail',
      component: GoodsDetail
    },
    {
      path: '/cart',
      name: 'Cart',
      component: Cart
    },
    {
      path: '/personalCenter',
      name: 'PersonalCenter',
      component: PersonalCenter
    }
  ]
});
  1. 页面间导航
    • template 中使用 <router - link> 标签进行导航,例如在商品列表页导航到商品详情页:
<template>
  <div>
    <ul>
      <li v - for="(item, index) in goodsList" :key="index">
        <router - link :to="{name: 'GoodsDetail', params: {id: item.id}}">{{item.name}}</router - link>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      goodsList: [
        {id: 1, name: '商品1'},
        {id: 2, name: '商品2'}
      ]
    };
  }
};
</script>
  • 在 JavaScript 代码中使用 this.$router.push 方法导航,例如在购物车页导航到个人中心页:
export default {
  methods: {
    goToPersonalCenter() {
      this.$router.push({name: 'PersonalCenter'});
    }
  }
};
  1. 路由状态恢复
    • 使用 history 模式(如上述配置),浏览器的历史记录会被正确管理。当用户刷新页面时,浏览器会根据当前 URL 匹配相应的路由,Vue Router 会根据配置找到对应的组件进行渲染。
  2. 传递商品ID到商品详情页
    • 在商品详情页组件 GoodsDetail.vue 中,可以通过 $route.params 获取传递过来的商品 ID:
export default {
  data() {
    return {
      goodsId: null
    };
  },
  created() {
    this.goodsId = this.$route.params.id;
    // 可以根据 goodsId 进行商品详情数据的请求
  }
};