同样是跳转,vue-router的与location.href有什么不同?

1,304 阅读1分钟

主要区别

1. vue-router

  1. vue-router使用pushState进行路由更新,静态跳转,页面不会重新加载;
  2. vue-router使用diff算法,实现按需加载,减少dom操作;
  3. vue-router是路由跳转或同一个页面跳转;
  4. vue-router是异步加载this.$nextTick(()=>{获取url})。

2. location.href

  1. location.href会触发浏览器,页面重新加载一次;
  2. location.href是不同页面间跳转;
  3. location.href是同步加载。

其他区别

1. vue-router跳转时可以携带参数

主页面跳转

toEditInfo() {
  this.$router.push({
       path: '/XXX/XXX',
       params:{
            edit:true
          }
    });
}

目标页面接收

created(){
  this.editStatus =  this.$route.query.params;
  console.log('editStatus',this.editStatus )
}

注意: 该方法传递的值不会在地址栏中显示,但刷新页面数据会消失

可以携带参数的传值

主页面

toEditInfo() {
  this.$router.push({
       path: '/XXX/XXX',
       query:{
            edit:true
          }
    });
}

目标页面接收

created(){
  this.editStatus =  this.$route.query.edit;
  console.log('editStatus ',this.editStatus )
}

该方法传递的值会在地址栏中显示,刷新页面数据不会消失

还可以进行动态路由拼接

2. 使用location.href实现页面div块的快速定位

location.href='#divClass'//<div id = "divClass"></div>,通过事件直接跳转到该dev

location.href可直接获取当前路径

parent.location.href跳转至上一层页面

top.location.href跳转至最外层页面