tags: ‘vue’, ‘路由’

categories: ‘vue’, ‘路由’

Vue Router获取当前页面由哪个路由跳转

问题:判断当前页面是由那个页面跳转过来的,如果上一个页面带有id则访问对应的步骤,否则为步骤一

可以使用beforeRouteEnter,具体代码如下:

  1. beforeRouteEnter (to, from, next) {
  2. next();
  3. console.log('当前页面路由', to, '上一个页面路由', from);
  4. },

例子:

此例子的操作是:

  1. 1step页面点击 `查看详情按钮` 进入detail详情页
  2. 2detail详情页点击 `回退或者继续操作按钮` 返回step页面
  3. 3step页面请求详情回到对应的步骤

step.vue

  1. <template>
  2. <div>
  3. <div v-if="code==1">步骤一</div>
  4. <div v-if="code==2">步骤二</div>
  5. <div v-if="code==3">步骤三</div>
  6. <Button @click="goRoute">查看详情</Button>
  7. </div>
  8. </template>
  9. <script>
  10. var _this = "";
  11. export default{
  12. data (){
  13. return {
  14. code: 1, // 步骤
  15. requestData: {
  16. id: 2, // 假设id为2
  17. }, // 数据
  18. }
  19. },
  20. methods: {
  21. // 获取详情
  22. getDetail(id){
  23. _this.code = id; // 假设传入的id就是当前步骤
  24. },
  25. // 跳转到详情页
  26. goRoute(){
  27. _this.$router.push({name:"detail", query: {id: _this.requestData.id}});
  28. }
  29. },
  30. created(){
  31. _this = this;
  32. },
  33. beforeRouteEnter (to, from, next) {
  34. next();
  35. // 如果不是从进行中的订单进来
  36. if(from.name == 'detail'){
  37. console.log('路由', to, from);
  38. if(from.query.id){
  39. from.query.id ? _this.getDetail(from.query.id) : '';
  40. }
  41. }
  42. },
  43. }
  44. </script>

detail.vue

  1. <template>
  2. <div>
  3. <Button @click="$router.push('step')">继续操作</Button>
  4. </div>
  5. </template>