1.vue-router基础
- vue-router的模式
- hash: 使用 URL hash 值来作路由。支持所有浏览器,包括不支持 HTML5 History Api 的浏览器。 #/home
- history: 依赖 HTML5 History API和服务器配置。【需要后端支持】 /home
- abstract: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。如果发现没有浏览器的API,路由会自动强制进入这个模式。【 这个模式不常用】
- hash/history常用于浏览器端,abstract用于服务端
- vue-router使用步骤
- 安装 vue-router yarn add vue-router
- 在src目录下创建一个router目录, 里面创建一个index.js文件 , 这个目录就是router的模块
- 引入第三方的依赖包, 并注册路由
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use( VueRouter ) //使用vue-router这个第三方插件
- 创建了一个router对象实例,并且创建路由表
const router = new VueRouter({
mode:'history'
routes })
- 导出router实例 export default router
- 入口文件main.js中引入路由实例 router ,然后在根实例中注册
import router from './router/index.js'
new Vue({
router,
render: (h) => App
}).$mount('#app')
- 路由表设置
const routes = [
{
path: '/',
redirect: '/home' //重定向
},
{
path: '/home',
component: Home
},
{
path: '*',
component: Error //错误路由设置
}
]
- vue-router二级路由
const routes = [
{
path: '/shopcar',
component: Shopcar,
children: [
{
path: 'yyb', //不写 /
component: Yyb
}
]
}
]
{
path: '/shopcar',
component: Shopcar,
//子路由
children: [
{
path: 'yyb', // 容易犯错点 /yyb X
component: Yyb,
name: 'yyb' //命名路由
},
]
},
<router-link :to = "{name:'yyb'}"/><router-link>
//在组件中数据绑定to属性以对象形式写入
- vue-router动态路由
<router-link :to = "{name: 'list',params: {id: xxx}, query: {xxx:xxx}}">
</router-link>
//使用prams时要修改相应路由表设置在路径后面加/:id
id: this.$route.params.id
query: this.$route.query.xxx