安装 | Vue Router 官网的相关用法
"vue-router": "^4.0.3",
如果你是 npm i vue-router
router>index.js
- import { createRouter, createWebHashHistory } from 'vue-router'
- import HomeView from '../views/HomeView.vue'
-
- const routes = [
- {
- path: '/',
- name: 'home',
- component: HomeView
- },
- {
- path: '/login',
- name: 'login',
- component: () => import(/* webpackChunkName: "about" */ '../views/LoginView.vue')
- },
- {
- path: '/register',
- name: 'register',
- component: () => import(/* webpackChunkName: "about" */ '../views/RegisterView.vue')
- },
- {
- path: '/search',
- name: 'search',
- component: () => import(/* webpackChunkName: "about" */ '../views/SearchView.vue')
- }
- ]
-
- const router = createRouter({
- history: createWebHashHistory(),
- routes
- })
-
- export default router
main.js
createApp(App).use(router)
一个router就完成了
通过定义meta:{show:true} 来决定显示与隐藏 router的原信息
<Footer v-show="$route.meta.show"/>
路由的跳转:
声明式导航: router-view
编程式导航: $router.push()
// 如果你的路由没有配置 :keyword 地址栏显示 xxx/#/search this.$router.push({name: 'search',params:{keyword: this.keyword}}) // 地址栏显示 xxx/#/search?k=大写字母 this.$router.push({path: '/search',query:{k: this.keyword.toUpperCase()}}) this.$route.params.keyword this.$route.query.k
// 如果要同时用params,query那么就只能是用name的写法 this.$router.push({name: 'search',params:{keyword: this.keyword},query:{k:this.keyword.toUpperCase()}}) 获取方式同上
// params 指定可传可不传
path: '/search/:keyword?' 其实在新版本中你不这么写路径也不会有问题,但是在地址栏是不会有参数出现的
// 如果你传的空字符串 新版本中其实也不会有路径问题,如果有就加上undefined this.$router.push({name: 'search',params:{keyword: '' || undefined},query:{k: this.keyword.toUpperCase()}})
props作为参数传递
props: ($route) => { return { keyword: $route.params.keyword, k: $route.query.k } }
简写:
props: ($route) => ({ keyword: $route.params.keyword, k: $route.query.k })
vue3不用重写push房费
vue2重写:
main.js
let originPush = VueRouter.prototype.push
let originPush = VueRouter.prototype.replace
// call 参数用逗号隔开,apply传递数组 篡改函数上下文一次
VueRouter.prototype.push = function (location,res,rej) {
if(res && rej) {
originPush.call(this,location,res,rej)
} else {
originPush.call(this,location,()=>{},()=>{})
}
}