必须get的小技巧-优雅实现页面刷新(vue)

前几天项目经理提了个需求要实现点击刷新按钮实现页面的局部刷新,刷新页面使用谷歌的重新加载不是就可以了何必要去自己开发呢?

结果自己尝试了一番发现只能实现全局的刷新,局部刷新还是比较捉急。

尝试

pushreplace这两个都方法都是vue-router提供的api。

在vue项目中使用this.$router.push()方法来跳转不同路径,如果跳转相同的路径的话会发现页面并没有刷新,而是在histry栈中添加了一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

使用this.$router.replace()方法报错vue-router.esm.js?8aaf:2065 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location这个是由于多次访问相同路由导致路由重复。

转化

将要刷新的路由和刷新后的路由之间通过一个桥梁(作为过渡)来连接。

将路由的信息和参数全部都传给"桥梁",当其跳转的一瞬间获取到参数和路由信息跳转到原来的路由。为了让用户无感知在跳转"桥梁"路由的时候使用replace方法不会向history中添加新的记录,在跳回原路由的时候是history方法,如果路由相同会替换之前的路由,而用户在点击浏览器回退按钮的时候悄然不知做了什么。

this.$router.replace({
    path: '/redirect' + fullpath
})

配置路由信息

{
    path: '/redirect/:path(.*)',
    component: () => import('@/views/redirect/index')
}

桥梁文件

<script>
export default {
  beforeCreate() {
    const { params, query } = this.$route
    const { path } = params
    this.$router.replace({ path: '/' + path, query })
  },
  render(h) {
    return h()
  }
}
</script>

更多文章https://clown-jack.github.io/

Vue.js中,要实现页面每隔一段时间自动刷新,通常会利用`Intersection Observer API`或者结合定时器`setTimeout`函数。这里提供两种常见的方法: 1. **使用Intersection Observer**: - 首先,安装`vue-popper`等库提供的`@popperjs/core`,因为它包含了一个简单的计时器组件`v-popover`,可以配合使用。 ```javascript import { Popper } from '@popperjs/core'; import { VPopover } from 'vue-popper'; export default { data() { return { refreshInterval: null, }; }, methods: { startAutoRefresh() { const observer = new IntersectionObserver((entries) => { if (entries[0].isIntersecting) { this.refresh(); } }); observer.observe(document.querySelector('your-target-element')); // 替换为你想要观察的目标元素 // 每隔指定时间(例如5秒)检查一次目标元素是否可见 this.refreshInterval = setInterval(() => observer.check(), 5000); }, stopAutoRefresh() { clearInterval(this.refreshInterval); }, refresh() { // 当目标元素进入视野时,执行刷新操作,如路由跳转、数据更新等 this.$router.push('/refresh-page'); // 或者this.$set(this, 'data', ...); 等 }, }, mounted() { this.startAutoRefresh(); }, beforeDestroy() { this.stopAutoRefresh(); }, }; ``` 2. **使用setTimeout和clearTimeout**: 如果没有第三方库支持,可以直接使用JavaScript的`setTimeout`和`clearTimeout`来设置定时任务。 ```javascript data() { return { autoRefreshTimeoutId: null, }; }, methods: { startAutoRefresh() { this.autoRefreshTimeoutId = setTimeout(() => { this.refresh(); this.startAutoRefresh(); // 递归调用直到停止 }, 5000); // 设定刷新间隔,单位毫秒 }, stopAutoRefresh() { clearTimeout(this.autoRefreshTimeoutId); }, refresh() { // 页面刷新内容,例如axios请求数据 axios.get('/refresh-url') .then(response => { // 更新视图 }) .finally(() => { // 清除定时任务后开始下一轮刷新 this.startAutoRefresh(); }); }, }, mounted() { this.startAutoRefresh(); }, beforeDestroy() { this.stopAutoRefresh(); }, ``` 记得替换上述代码中的`your-target-element`和`/refresh-page`为实际的元素选择器和刷新路径。在适当的时候调用`stopAutoRefresh`方法来停止刷新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值