一、Vue如何获取当前页面的url,获取路由地址
1.完整url可以用 window.location.href
2.路由路径可以用 this.$route.path
3.路由路径参数 this.$route.params 例如: this.$route.params.id
4.路由查询参数 this.$route.query 例如: /user/search?name=sf → this.$route.query.name
二、vue地址栏直接输入路由无效问题
vue 在页面上显示哪个组件是根据 vue-router 进行控制的,在地址栏上直接输入路由名称,并不能触发 vue-router 的规则,所以只能通过监听地址的改变,利用回调函数在组件内部进行动态修改路由。
hash 就是 URL 地址中 # 字符后面的字符串,通过监听 hash 的状态,来动态修改 vue-router 的路由,当 hash 被修改时,将触发 hashchange事件
解决监听hashchange事件
mounted(){
window.addEventListener('hashchange',()=>{
var currentPath = window.location.hash.slice(1); // 获取输入的路由
if(this.$router.path !== currentPath){
this.$router.push(currentPath); // 动态跳转
}
},false);
}
三、vue如何在页面刷新时保留状态信息
1.通过本地存储数据
localstorage.setItem('state', JSON.stringify(this.$store.state))
// 页面加载的时候在created中获取本地存储中的数据
localStorage.getItem('state') && this.$store.replaceState(JSON.parse(localStorage.getItem('state')));
四、npm报错 This is probably not a problem with npm,there is likely additional logging output above可能的原因
npm i