Vue Router怎么配置路由
以vue2为例
一、安装 Vue Router
npm install vue-router@3
二、项目结构(建议)
src/
├── views/ // 页面组件
│ ├── Home.vue
│ └── About.vue
├── router/
│ └── index.js // 路由配置
├── App.vue
└── main.js
三、配置路由(router/index.js)
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
// 组件导入
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
Vue.use(VueRouter) // 安装 Vue Router 插件
const routes = [
{
path: '/', // 路径
redirect: '/home' // 重定向
},
{
path: '/home',
name: 'Home',
component: Home // 路由组件
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = new VueRouter({
mode: 'history', // 路由模式:hash(默认)或 history
routes // 路由表
})
export default router
四、挂载路由(main.js)
// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
new Vue({
router, // 挂载 router
render: h => h(App)
}).$mount('#app')
五、在 App.vue 中显示页面组件
<template>
<div id="app">
<router-view /> <!-- 页面容器,动态渲染路由组件 -->
</div>
</template>
六、导航方式总结(Vue 2)
声明式导航(模板中使用)
<router-link to="/home">首页</router-link>
<router-link :to="{ name: 'About' }">关于</router-link>
编程式导航(JS 中跳转)
this.$router.push('/home')
this.$router.push({ name: 'About' })
this.$router.push({ path: '/search', query: { key: 'vue' } })
返回上一页
this.$router.go(-1)
七、支持嵌套路由、路由守卫、404页面等
const routes = [
{
path: '/admin',
component: AdminLayout,
children: [
{
path: 'dashboard',
component: Dashboard
}
]
},
{
path: '*',
component: NotFound
}
]
浙公网安备 33010602011771号