vue面试(一)

1. 路由传参,name和path的区别

// 字符串形式
 //编程式导航(路由)
      this.$router.push(`/home/12?newscontent=marco`)//就是实现路由链接的效果
      

   //命名路由  对象形式
   //用name跳转的方式可以实现带参数,而且不在页面显示,**注意用path跳转的话,params是不生效的**
      const location = {
        name: "home",
        params: { nid: 12},
        query: { newscontent: 'marco '},
      };  
    this.$router.push(location)   
//path传参
this.$router.push({path:'/home',query: {id:'1'}})


this.$router.push({name:'home',params: {id:'1'}})  // 只能用 name
//router 路由配置 path: "/home/:id"  ,
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
{
    path:'/home/:id',
    component:Home,    
    name:'home'
}

name 和 path 跳转的区别在于

1.name命名 传参用 params和query, path属性传参,不能用params,会无效
2.router 路由x需要配置 path: “/home/:id” ,不然页面的id不会保留

2.路由守卫

2.1.全局前置路由守卫router.beforeEach

import routes from '@/router/routes'
const router = new VueRouter({
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

//添加全局前置路由导航守卫
// 必须登录后才能访问的多个界面使用全局守卫(交易相关、支付相关、用户中心相关) 
// 自动跳转前面想而没到的页面

router.beforeEach((to, from, next) => {
  //to:代表路由对象,目标(想去哪)
  //from: 代表路由对象,起始(从哪来)
  //netx:是一个函数,选择放行或者不放行的意思还可以去重定向到一个新的地方  
  //next()就是放行
  //next(false)不放行
  //next(路径)重定向

  let targerPath = to.path
  if(targerPath.startsWith('/pay') || targerPath.startsWith('/trade') || targerPath.startsWith('/center')){
    //看看用户是否登录了
    if(store.state.user.userInfo.name){
      next()
    }else{
      //在登录的路径后面添加上之前想要去的路径
      //配合登录逻辑可以让我们去到之前想去而没有去的地方
      next('/login?redirect='+targerPath)
    }
  }else{
    next()
  }

})

export default router

全局解析守卫

在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

全局后置钩子

你也可以注册全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身:

router.afterEach((to, from) => {
  // ...
})

路由独享的守卫

你可以在路由配置上直接定义 beforeEnter 守卫:

  {
    path:'/addcartsuccess',
    component:AddCartSuccess,
    beforeEnter: (to, from, next) => {
      let skuNum = to.query.skuNum
      let skuInfo = sessionStorage.getItem('SKUINFO_KEY')
      if(skuNum && skuInfo){
        next()
      }else{
        next('/')
      }
    }
  },

组件内的守卫

 beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    // 如果内部需要用到this,那么就得用下面的那个写法
    if (!store.state.user.userInfo.name) {
      //没有登录,放行
      next();
    } else {
      //登录了,跳转到home页面
      next("/home");
    }
  },
  
   // beforeRouteEnter(to, from, next) {
  //   next((vm) => {
  //     // 通过 `vm` 访问组件实例 vm就是你之前想要的this
  //   });
  // },

本地开发 没有任何问题 部署服务器 404等问题

评论

暂无评论