Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

vue.js - position scrollY no changed when route change - vuejs

When I clicked to set size of product in div of class 'select__item',my route: this.$router.push({ query: { ...this.$route.query, size: value } }) ,no refresh page, only url change and scroll back to top. I want position scrollY no changed when I click set size for product. Thank you for help me .Here is my code:

Product.vue

<Product>
<!--some component-->
    <Sizes>
    </Sizes>

</Product>

Sizes.vue

<Sizes>
            <div class="select__items no-scrollbar">
                <div
                    v-for="size in product.sizes"
                    :key="size.id"
                    :class="['select__item', { active: size.id == currentSizeId }]"
                    :title="size.name"
                >
                    <button class="select__label" @click="currentSizeId = size.id">
                        {{ size.name }}
                    </button>
                </div>
            </div>
</Sizes>

computed

computed: {

    currentSize() {
        return this.product.sizes.find((s) => s.id == this.currentSizeId)
    },
    currentSizeId: {
        get() {
            this.$nuxt.$emit('setsize', this.$route.query.size)
            return this.$route.query.size
        },
        set(value) {
            if (this.currentSizeId == value) {
                return
            }
            this.$router.push({ query: { ...this.$route.query, size: value } })
        },
    },
},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Default case in VueJs is to keep Yscroll position when changing page.

You can change your vue-router setting to scroll to the top of your page each time you changing it;

There is a StackOverflow here: https://stackoverflow.com/a/50901500/12592396

And a more compete answer here: https://stackoverflow.com/a/52111880/12592396

The short anwser is to define scrollBehavior on your Router:

export default new Router({
    mode: ...,
    routes: [
        ...
    ],
    scrollBehavior (to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...