【问题标题】:Vue navigate to next route after 10 secondsVue 在 10 秒后导航到下一条路线
【发布时间】:2018-09-16 17:56:45
【问题描述】:

我打算用 Vue 制作一个信息屏幕。目前我有两种观点。

第一个视图在 10 秒后导航到第二个视图,反之亦然。

<template>
<div v-if="posts && posts.length">
    <table>
        <tr>
            <th>Name</th>
            <th>Start</th>
            <th>Project</th>
            <th>Activity</th>
        </tr>
        <tr v-for="post of posts">
            <td>{{post.userName}}</td>
            <td>{{post.start}}</td>
            <td>{{post.projectName}}</td>
            <td>{{post.activityName}}</td>
        </tr>
    </table>
</div>

<div v-else-if="errors && errors.length">
    <h1>error connecting to API</h1>
</div>

<script>
    import axios from "axios";

    export default {
        data() {
            return {
                posts: [],
                errors: [],
                interval: null
            };
        },
        methods: {
            loadData() {
                axios
                    .get(
                        `http://myapi.com/infoscreen.php`
                    )
                    .then(response => {
                        this.posts = response.data;
                    })
                    .catch(e => {
                        this.errors.push(e);
                    });
            }
        },
        created() {
            this.loadData();
            this.interval = setInterval(
                function () {
                    this.$router.push({path: "/issues"});
                }.bind(this),
                10000
            );
        }
    };
</script>

到目前为止,代码工作正常,10 秒后重定向到路由问题发生。一旦路由问题在 10 秒后加载,它就会从代码示例导航回页面活动页面。

似乎还有区间集。因为现在在 9.x 秒后会发生重定向,并且发生的重定向越多,直到浏览器崩溃,它的速度就会越来越快。

那么有没有一种最佳做法,比如从 router.js 获取所有路由,然后在 10 秒后导航到下一页?

感谢您的帮助。

【问题讨论】:

  • 重定向时清除间隔?
  • 清除@Li357所说的间隔或使用setTimeout重定向

标签: javascript vue.js vue-router


【解决方案1】:

有两件事。如果您希望使用setInterval,请使用clearInterval 清除间隔。使用beforeDestroy 钩子来做到这一点。

或者更好的是,使用setTimeout 而不是setInterval。使用setTimeout,您无需清理计时器。这是推荐的方法。

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2020-01-14
    • 1970-01-01
    • 2022-07-18
    • 2018-08-04
    • 1970-01-01
    相关资源
    最近更新 更多