首页 > 解决方案 > 即使我更改路线,Vue 方法也会运行,仅当我在特定路线/组件上时如何运行方法?

问题描述

我正在从 Wordpress API 检索帖子,并且在滚动时我想加载更多帖子并且它可以工作。但是,每当我在底部滚动时单击帖子以打开另一条路线时,应用程序都会调用 API,它基本上会scroll()从其他组件运行该方法。我正在使用 vue-router 和 axios。

家庭组件:

    <template>
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <!--       Post         -->
                <div class="col-md-4 mb-4" v-for="post in posts" :key="post.id">
                    <div class="card h-100">
                        <div style="overflow: hidden">
                            <img class="card-img-top img-fluid" v-bind:src="post._embedded['wp:featuredmedia']['0'].source_url" alt="Card image cap">
                        </div>
                        <div class="card-body">
                            <router-link :to="{ path: '/article/' + post.slug, query: { id: post.id }, params: { title: post.slug }}">
                                <h5 class="card-title">{{ post.title.rendered }}</h5>
                            </router-link>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

import axios from 'axios';

    export default {
        name: "Home",
        data(){
            return {
                posts: [],
                errors: [],
                pagination: 2,
                totalPages: null
            }
        },

        // Fetches posts when the component is created.

        methods: {
            getPosts() {
                axios.get('https://example.com/wp-json/wp/v2/posts?_embed')
                    .then(response => {
                        // JSON responses are automatically parsed.
                        this.posts = response.data;
                        this.totalPages = response.headers['x-wp-totalpages'];
                    })
                    .catch(e => {
                        this.errors.push(e)
                    });
            },

            scroll () {
                window.onscroll = () => {
                    let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight === document.documentElement.offsetHeight;

                    if (bottomOfWindow) {
                        if(this.pagination <= this.totalPages) {
                            axios.get('https://example.com/wp-json/wp/v2/posts?_embed&&page=' + this.pagination)
                                .then(response => {
                                    this.posts = this.posts.concat(response.data);
                                    this.pagination = this.pagination + 1;
                                });
                        }
                    }
                };
            }
        },
        beforeMount() {
            this.getPosts();
        },

        mounted() {
            this.scroll();
        }

    }


</script>

<style scoped lang="scss">
    h1{
        font-weight: 300;
    }
    .card-body{
        a{
            color: #00b6f1;
            text-decoration: none;
            transition: 0.2s ease-in-out;

            &:hover{
                color: #62d4f9;
            }
        }
    }
</style>

单个帖子组件:

<template>
    <div class="container-fluid">
        <div class="container">
            <div class="row">
                <div class="col-12 text-center mt-5 mb-5">
                    <img class="img-fluid" :src="featuredImage" alt="Card image cap">
                </div>
                <div class="col-12">
                    <h1>{{ title }}</h1>
                </div>
                <div class="col-12 content">
                    <p v-html="content">{{ content }}</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import axios from "axios";


    export default {
        name: "Single",
        data(){
            return {
                post: {},
                featuredImage: null,
                errors: [],
                title: null,
                content: null,
            }
        },

        methods:{
            getPost() {
                axios.get('https://example.com/wp-json/wp/v2/posts/'+this.$route.query.id+'?_embed')
                    .then(response => {
                        // JSON responses are automatically parsed.
                        this.post = response.data;
                        this.featuredImage = response.data._embedded['wp:featuredmedia']['0'].source_url;
                        this.title = response.data.title.rendered;
                        this.content = response.data.content.rendered;
                    })
                    .catch(e => {
                        this.errors.push(e)
                    })
            },
        },
        beforeMount() {
            this.getPost();
        },
    }

</script>

<style lang="scss">
    .content{
        img, iframe{
            max-width: 100%;
            height: auto;
            margin: auto;
            display: block;
            margin-top: 30px;
            margin-bottom: 30px;
        }

        iframe{
            height: 300px;
        }

        p{
            color: #767676;
            font-size: 14px;
            line-height: 24px;
            font-weight: 400;
        }

        h2{
            color: black;
        }

        a {
            color: #00b6f1;
            text-decoration: none !important;
            transition: 0.2s ease-in-out;

            &:hover{
                color: #62d4f9;
            }
        }
    }
</style>

标签: javascriptvue.jscomponentsvue-componentvue-cli-4

解决方案


试试这个Home.vue

beforeDestroy() {
  this.scroll = null
  delete this.scroll
}

发生这种情况是因为,在更改路线时,该scroll()方法仍处于挂载状态。这应该可以防止它被加载到Home.vue.


推荐阅读