Vue 在 10 秒后导航到下一条路线

Vue navigate to next route after 10 seconds

我打算用 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 秒后加载路由问题后,它会导航回代码示例中的页面 activity 页面。

好像还有间隔集。因为现在 9.x 秒后会发生重定向,并且重定向会越来越快,直到浏览器崩溃。

那么,是否有最佳做法可以执行某些操作,例如从 router.js 获取所有路由,然后在 10 秒后导航到下一页?

感谢您的帮助。

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

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