vue2 和 vue3 路由使用对比

 以跳转至/detail 页面,传递id:1举例:

  vue2 vue3

路由跳转

(通过query)

 
//<router-link>跳转
<router-link :to="{ path:'/detail',query:{id:1} }">
详情
</router-link>

//path可替换成name,写法如下:
<router-link :to="{ name:'detail',query:{id:1} }">
详情
</router-link>


//js跳转
this
.$router.push({ path: '/detail', //path可替换成name query: { id:1 }, });

 

//<router-link>跳转 同vue2


//js跳转
//需要先引入useRouter,执行useRouter()
import { useRouter } from 'vue-router';

const router = useRouter();

router.push({
    path: '/detail',
    query: { id:1 }
});
 

 

路由跳转

(通过params)

 

//<router-link>跳转
<router-link :to="{ path:'/detail',params:{id:1} }">
详情
</router-link>
//path可替换成name,写法如下:
<router-link :to="{ name:'detail',params:{id:1} }">
详情
</router-link>


//js跳转
this
.$router.push({   path: '/detail',//path可替换成name   params: {     id: 1,   }, });

 

 
//<router-link>跳转 同vue2

//js跳转
//需要先引入useRouter,执行useRouter()
import { useRouter } from 'vue-router';
const router = useRouter();
router.push({
    path: '/detail', //path可替换成name
  params:{
    id:1
  }

});

 

 获取路由参数

(通过query方式传递的)

 
const id = this.$route.query.id

 

 
//需要先引入useRoute,执行useRoute()
import { useRoute } from 'vue-router';
const route = useRoute();

const id = route.query.id

 

 

获取路由参数

(通过params方式传递的)

 
const id = this.$route.params.id

 

 
//需要先引入useRoute,执行useRoute()
import { useRoute } from 'vue-router'; const route = useRoute(); const id = route.params.id

 

总结

$route:获取路由信息对象,只读;

$router:操作路由对象 ,只写。 

posted @ 2022-04-01 11:25  前端[色色]  阅读(432)  评论(0编辑  收藏  举报