Vue метод работает, даже если я изменяю маршрут, как запустить метод, только если я нахожусь на указанном c маршруте / компоненте? - PullRequest
0 голосов
/ 08 марта 2020

Я получаю сообщения из Wordpress API, и при прокрутке я хочу загрузить больше сообщений, и это работает. Но всякий раз, когда я щелкаю по сообщению, чтобы открыть другой маршрут, когда прокручиваю внизу, приложение вызывает API, оно в основном запускает метод scroll() из другого компонента. Я использую vue роутер и топор ios.

Домашний компонент:

    <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>

1 Ответ

0 голосов
/ 08 марта 2020

Попробуйте это в Home.vue:

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

Это происходит потому, что при изменении маршрута метод scroll() все еще монтируется. Это должно предотвратить загрузку в другом месте, чем в Home.vue.

...