写作背景:主要是想将自己之前忽略的一些知识点补充上,避免自己以后又忘记了,vue2.0
vue-router
1.pathMatch 最近业务中总会遇到这个参数,就是不知道从哪里来的
当使用一个通配符时,$route.params 内会自动添加一个名为 pathMatch 参数。它包含了 URL 通过通配符被匹配的部分:
// 给出一个路由 { path: '/user-*' }
this.$router.push('/user-admin')
this.$route.params.pathMatch // 'admin'
// 给出一个路由 { path: '*' }
this.$router.push('/non-existing')
this.$route.params.pathMatch // '/non-existing'
2.404,通配符
捕获所有路由或 404 Not found 路由
常规参数只会匹配被 / 分隔的 URL 片段中的字符。如果想匹配任意路径,我们可以使用通配符 (*):
{
// 会匹配所有路径
path: '*'
}
{
// 会匹配以 `/user-` 开头的任意路径
path: '/user-*'
}
当使用通配符路由时,请确保路由的顺序是正确的,也就是说含有通配符的路由应该放在最后。路由 { path: ‘*’ } 通常用于客户端 404 错误。如果你使用了History 模式,请确保正确配置你的服务器。
3.路由优先级
同一个路径可以匹配多个路由,此时,匹配的优先级就按照路由的定义顺序:路由定义得越早,优先级就越高
4.vue动态路由加载时 Cannot find module xxx
webpack4中 import 引入不能使用变量,可以使用静态常量
eg:
import (‘@/views/about.vue’)
5.scrollBehavior 滚动行为
tips:这个功能只在支持 history.pushState 的浏览器中可用
scrollBehavior 方法接收 to 和 from 路由对象。第三个参数 savedPosition 当且仅当 popstate 导航 (通过浏览器的 前进/后退 按钮触发) 时才可用。
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
// return 期望滚动到哪个的位置
}
})
平滑滚动
只需将 behavior 选项添加到 scrollBehavior 内部返回的对象中,就可以为支持它的浏览器 (opens new window)启用原生平滑滚动:
scrollBehavior (to, from, savedPosition) {
if (to.hash) {
return {
selector: to.hash,
behavior: 'smooth',
}
}
}
6.vuex
getter 不能直接更改,但是state里面的数据可以更改
getter是个计算属性,不能直接更改,是随着state自己的更改而更改。state能做修改
7.vue hash 模式下,跳转页面的时候路由变了但是页面没有发生变化
app.vue中
mounted () {
// 检测浏览器路由改变页面不刷新问题,hash模式的工作原理是hashchange事件
window.addEventListener('hashchange', () => {
let currentPath = window.location.hash.slice(1)
if (this.$route.path !== currentPath) {
this.$router.push(currentPath)
}
}, false)
},