关于vue.js: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等问题

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理