vue的路由分为静态路由和动态路由,对于静态路由,就是使用router-link的方式进行的,下面我们只对动态路由进行介绍,并且只是vue的动态路由的常用方式。
- 不管是静态路由和动态路由,都需要进行路径和组件的配置,就是在vue项目中的router文件夹下的index.js文件进行配置,配置的方式也是分为两种,一种是静态引入一种是动态引入:
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
},
一般在我们项目创建的时候都有这两个,path和name都配上,如何component分为静态和动态,对于动态而言,就是说是一种按需加载和局部更新吧。
- 配置好了组件我们应该怎么动态路由呢?我们这里也只是介绍this.$router.push的方式,我们需要进行router组件的注册(在mian.js文件中),不然用不了:
import router from './router'
//第一种方式,推荐使用
new Vue({
router,}).mount('#app')
//第二种方式,挂载到Vue的原型上
Vue.prototype.$router=router
- 配置好了之后就可以进行使用了,一般也是两种方式,一种是name->params,另外一种是path->query,刚好对应我们上面router的组件路由的name和path。
//name->params方式
this.$router.push({
name:'user',
params:{
id:123
}
})
//path->query方式
this.$router.push({
path:'/user',
query:{
id:123
}
})
- 其实就是对应的router里面各自组件的配置,挺巧妙的,然后既然我们传递了参数,那么必然是需要接收参数的,参数的接收是根据路由来的,分为this.route.query,一般这种接收参数的事情都是在调用对应逻辑需要使用到的:
//name->params
created(){
console.log(this.$route.params.id)
}
//path->query
created(){
console.log(this.$route.query.id)
}
对此,这些就是vue的动态路由传递参数和接收参数的方式。