import HelloWorld from ‘…/HelloWorld.vue’
//Vue路由:配置路由
const routes = [
{path: ‘/home’, component: BYHome},
{path: ‘/news’, component: BYNews},
{path: ‘/helloworld’, component: HelloWorld},
{path: ‘*’, redirect: ‘/home’} /*默认跳转路由 */
]
//Vue路由:实例化VueRouter
const router = new VueRouter({
routes //缩写,相当于 routes:routes
})
//Vue路由:需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中
/* */
//暴露出去
export default router;
3.在main.js中
//Vue路由:引入路由文件
import router from ‘./components/jsTool/router.js’
new Vue({
router, //Vue路由:挂载路由
render: h => h(App),
}).$mount(’#app’)
4.Vue路由:根组件的模板里面放上下面这句话,需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中
5.路由跳转
首页
新闻
helloWorld
三、路由动态传值:
1.获取路由的get传值
//路由配置
import BYHomeDetail from ‘…/BYHomeDetail.vue’
{path: ‘/homeDetail’, component:BYHomeDetail},
//跳转时跟get参数
{{listItem.title}}
//子页面获取路由的get传值
mounted(){
console.log(this.$route.query);
}
2.动态路由传值
//路由配置:带形参
import BYNewDetail from ‘…/BYNewDetail.vue’
{path: ‘/newDetail/:aid’, component: BYNewDetail},
//跳转时传值
{{key}}–{{item}}
//子页面获取动态路由传值
mounted(){
console.log(this.$route.params);
}
四、路由的跳转方式:
第一种跳转方式:编程式导航
{path: ‘/news’, component: BYNews},
this.$router.push({path:‘news’});
带参:
{path: ‘/newDetail/:aid’, component: BYNewDetail},
this.$router.push({path:‘/newDetail/495’});
第二种跳转方式:命名路由
{path: ‘/news’, component: BYNews,name:‘news’},
this.$router.push({name:‘news’});
带参:
this.$router.push({name:‘news’,params:{userId:123}});
五、路由的hash模式以及history模式:
默认是hash模式,路由上方的路径是用#表示,http://localhost:8080/#/news
可以将hash模式改为history模式,路由上方的路径就没有了
#,http://localhost:8080/news
如果有history模式,需要后台做一些配置
//Vue路由:实例化VueRouter
const router = new VueRouter({
mode: ‘history’, //若是默认的hash模式,则mode不需要写
routes //缩写,相当于 routes:routes
})
六、路由的嵌套
User.vue页面中有两个子页面
UserAdd.vue
UserList.vue
//路由的配置
import BYUser from ‘…/BYUser.vue’
import UserAdd from ‘…/User/UserAdd.vue’
import UserList from ‘…/User/UserList.vue’
{path: ‘/user’ , component:BYUser,
children:[
{path: ‘useradd’,component:UserAdd},
{path: ‘userlist’,component:UserList}
]
},
//路由的跳转
增加用户
用户列表
七、登录及首页的路由配置说明
1.创建一个localstorage本地存储类storage.js,用来记录登录状态
var storage={
set(key,value){
console.log(“storage---->”)
console.log(value)
localStorage.setItem(key, JSON.stringify(value));
},
get(key){
return JSON.parse(localStorage.getItem(key));
},remove(key){
localStorage.removeItem(key);
}
}
export default storage;
2.创建一个自定义的路由表:router.js
import Vue from ‘vue’;
//引入路由
import VueRouter from ‘vue-router’
Vue.use(VueRouter)
//设置路由表
最后
喜欢的话别忘了关注、点赞哦~
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】