返回

VUE Hash模式分享/缓存/传参遇到的坑

前端

VUE Hash模式分享至QQ出现404

使用vue路由的hash模式时,可能会遇到分享至QQ后出现404的情况。这是因为QQ默认对Hash路由模式不支持,在分享时会忽略哈希符号(#),导致页面找不到。

解决办法:

  1. 在index.html中添加<base href="#/">标签,以告知浏览器,所有链接都应该以#作为根目录。
  2. 在分享时,在链接后面添加#号,例如:https://example.com/#/home

Vue页面缓存失败,缓存的页面重新进入不刷新

在Vue项目中,可能会遇到页面缓存失败,导致缓存的页面重新进入不刷新或显示错误内容的情况。这是因为Vue在切换路由时,会将当前页面的HTML和JS缓存起来,以提高页面加载速度。但是,当缓存的页面内容发生变化时,缓存就会失效,导致页面无法正常显示。

解决办法:

  1. 在router.js中,设置cache: false,以禁止Vue缓存页面。
  2. 使用keep-alive组件来控制页面的缓存。
  3. 在页面切换时,手动清除缓存。

Vue Hash模式路由跳转设置布尔值最好转为字符串

在Vue Hash模式中,路由跳转时设置布尔值可能会出现问题。这是因为布尔值在解析时,会被转换为字符串"true"或"false",导致路由无法正确匹配。

解决办法:

将布尔值转换为字符串,例如:

this.$router.push({ path: '/home', query: { active: 'true' } })

结语

本文分享了VUE Hash模式下分享至QQ出现404,页面缓存失败,以及路由跳转设置布尔值最好转为字符串的解决办法。希望对大家有所帮助。

附录:代码示例

// index.html
<base href="#/">

// router.js
const router = new VueRouter({
  mode: 'hash',
  cache: false,
  routes: [
    { path: '/', component: Home },
    { path: '/home', component: Home },
    { path: '/about', component: About },
  ]
})

// App.vue
<template>
  <div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
  router
}
</script>
// Home.vue
<template>
  <div>
    <h1>Home</h1>
    <p>This is the home page.</p>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>
// About.vue
<template>
  <div>
    <h1>About</h1>
    <p>This is the about page.</p>
  </div>
</template>

<script>
export default {
  name: 'About'
}
</script>

参考文献

  1. Vue Router文档
  2. Vue.js官方网站