vue路由写法小结
    		       		warning:
    		            这篇文章距离上次修改已过452天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue.js中,使用Vue Router可以实现应用的路由功能。以下是Vue Router的常见写法小结:
- 安装和引入Vue Router:
 
npm install vue-router
import VueRouter from 'vue-router'- 使用Vue.use注册插件:
 
Vue.use(VueRouter)- 创建路由实例并传入路由映射:
 
const router = new VueRouter({
  routes: [
    { path: '/path1', component: Component1 },
    { path: '/path2', component: Component2 },
    // 更多路由规则...
  ]
})- 将路由实例挂载到Vue实例上:
 
new Vue({
  router,
  // 其他选项...
}).$mount('#app')- 在Vue模板中使用
<router-link>和<router-view>: 
<router-link to="/path1">Go to Path1</router-link>
<router-link to="/path2">Go to Path2</router-link>
 
<router-view></router-view>- 使用编程式导航进行路由跳转:
 
// 在Vue组件内部
this.$router.push('/path1')- 使用命名路由和参数:
 
const router = new VueRouter({
  routes: [
    { name: 'user', path: '/user/:id', component: UserComponent }
  ]
})
 
// 导航到路由并传递参数
this.$router.push({ name: 'user', params: { id: 123 }})- 使用重定向和别名:
 
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/path1' },
    { path: '/b', component: ComponentB, alias: '/path2' }
  ]
})- 嵌套路由(路由视图嵌套):
 
const router = new VueRouter({
  routes: [
    {
      path: '/parent',
      component: ParentComponent,
      children: [
        { path: 'child1', component: ChildComponent1 },
        { path: 'child2', component: ChildComponent2 }
      ]
    }
  ]
})- 使用路由守卫进行身份验证或访问控制:
 
router.beforeEach((to, from, next) => {
  if (需要验证的条件) {
    next(); // 继续
  } else {
    next(false); // 中断
  }
})这些是Vue Router的常用写法,可以根据项目需求灵活使用。
评论已关闭