vue3笔记_引入vue-router

126 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情

在单页应用上自由导航,vue3提供了相应的router组件

安装vue-router

cd hello-world
npm install vue-router@4

入门路由

使用router-link进行组件导航,路由到2个例子组件页面

在components创建2个vue组件: home.vue和about.vue,内容为This is home|about

在src目录下创建一个router.js页面,来配置vue-router

//引入创建路由和策略方法
import { createRouter, createWebHashHistory } from 'vue-router'

//引入刚刚写的组件
import About from './components/about'
import Home from './components/home'

//配置路径
const routes = [
    { path: "/home",  component: Home},
    { path: "/about", component: About},
]

const router  = createRouter({
    history: createWebHashHistory(),
    routes: routes,
})

//导出
export default router

在main.js页面挂载刚刚创建的路径配置

import router from './router'
app.use(router)

在App.vue页面弄个div将组件内容展出来

  <div>
      <p>
        <router-link to="/home">Go to Home</router-link>
        <br>
        <router-link to="/about">Go to about</router-link>
        <router-view></router-view>
      </p>      
  </div>

然后启动该项目,在页面上点击 Go to Home 和Go to about,下方会展示该组件的内容,非常简单的就实现了一个单页应用小demo

image.png

路由页还有一种更加流行的写法,无法显示声明导入组件,直接在对象中引入

import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
    { path: "/home", name: "home", component: () => import('./components/home.vue'), },
    { path: "/about", name: "about", component: () => import('./components/about.vue'), },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes,
})

export default router

动态路由和路由传参,以及嵌套路由

上面的例子属于静态路由,固定路径的,以下例子是动态路由,

const routes = [
    { path: '/about/:id', component: () => import('./components/about.vue'),},
]

在about.vue页面中div内加入如下内容,既可看到相应的传参

{{ $route.params.id }}

路由传参可以在组件中导航时,将组件数据带给另一个组件(另一种组件通信方式)

methods: {
  test2(index) {
      this.$router.push({name:'deploy',params: {num:this.tableData[index]}})
    }
}    

嵌套路由类似子菜单,一个主菜单,多个子菜单

{
    path: '/home',
    component: Home,
    redirect: '/home/table',
    name: '项目1',
    children: [
      {
        path: 'home1',
        name: 'home1',
        component: () => import('@/components/home1'),
      },
      {
        path: 'home2',
        name: 'home2',
        component: () => import('@/components/home2'),
      }
    ]
  },

至此,简单的vue-router使用就基本明了