Router
1.路由核心模块 import VueRouter from ‘vue-router’
2.注册路由插件 Vue.use(VueRouter)
3.路由映射表
const routes = [
{
path: '/film', --路径
component: Film --跳转页面组件名(组件需引入)
children: [ --子组件
{
path: '/film/nowplay', --路径
component: Nowplay --跳转页面组件名(组件需引入)
},
{
path: '/film', --路径
redirect: '/film/nowplay' --跳转路径
}
]
}
]
4.组件路由跳转:声明式导航 && 编程式导航(JS跳转)
1.声明式导航:
<router-link to="/film" tag="li" activeClass="a"></router-link>
to -->点击后跳转页面路径
tag -->定义当前标签
activeClass -->高亮显示,自定义class
2.编程式导航:
a.定义事件: @click="handleClick(item.filmId)"
b.切换页面: this.$router.push(`/Nowlist/${id}`)
c.引入组件: import Nowlist from '@/views/Film/Nowlist'
d.匹配进入路径: const routes = [{
path: '/Nowlist/:id', // 具体影片,传递id
component: Nowlist
}]
路由命名 ($route.name 获取路由命名的名字)
5.重定向和别名
const routes = [
{
path: '/', --匹配进入路径
redirect: '/film' --跳转页面组件名(组件需引入)
},
{
path: '*', --匹配所有路径
redirect: '/Error' --跳转页面组件名(组件需引入)
},
{
path: '/a', --匹配所有路径
redirect: '/Error', --跳转页面组件名(组件需引入)
alias: '/b' -- 路由路径别名
}
]
6.路由传递id
- 点击事件传递id: @click="handleClick( Id )"
- 跳转页面附带id: methods: {
handleClick (id) {
this.$router.push(`/Nowlist/${id}`) // 切换页面
}
}
- router引入需要跳转的页面: import Nowlist from '@/views/Film/Nowlist'
- 定义跳转页面需要携带的id: const routes = [
{
path: '/Nowlist/:id', // 具体影片,传递id
component: Nowlist
}
7.懒加载
const routes = [
{
path: '/Cinema', --匹配进入路径
component: ()=>import('@/viees/Cinema') --跳转页面组件路径(组件用时再引入)
component: ()=>import(/* webpackChunkName:'myName'*/'@/viees/Cinema')
-- 自定义Name
}
]
8.登录阻拦
单个拦截:
1.登录页点击事件:
handleClick () {
localStorage.setItem('token',JSON.stringify({isLogin:true}))
this.$router.push('/center')
}
2.阻拦页阻止事件:
beforeRouteEnter (to, from, next) {
if(localStorage.getItem('token')){
next()
}else{
console.log('重定向,回到log页面');
next('/center/log')
}
}
全局拦截
3.配置全局路由守卫(拦截)
router.beforeEach((to,from,next)=>{
// console.log(to) //跳转的是center才拦截
if(to.path=== '/center'){
// console.log("被拦截")
if(localStorage.getItem("token")){
next()
}else{
console.log('重定向到 login页面')
next("/login")
}
}else{
next()
}
})
9.HTML5 History模式: mode 参数:
-
history: /home
-
hash : #/home
const router = new VueRouter({
mode: ‘history’,
routers
})
10.路由原理
(1)hash路由 ==> location.hash 切换
window.onhashchange 监听路径的切换
(2)history路由==> history.pushState 切换
window.onpopstate 监听路径的切换
11.判断是否在服务器环境下运行
var url = process.server ? 'http://m.maoyan.com' : ''
通信方式
常见使用场景可以分为三类:
父子通信:
- 父子组件通信方式一 (props / $emit)
- 父子组件通信方式二 (ref / $refs)
兄弟通信:
- 中央事件总线
main.js : Vue.prototype.bus = new Vue();
页面 :
this.bus.$emit(事件名,data);
this.bus.$on(事件名,(data)=> {});
- Vuex
跨级通信:
中央事件总线 Bus;Vuex;