randolphtellis / vue3-pdfjs

PDF Reader for Vue 3 using Mozilla's PDF.js
MIT License
92 stars 17 forks source link

Question regarding loading pages dynamically #7

Closed JaavierR closed 2 years ago

JaavierR commented 2 years ago

Hi @randolphtellis,

First of all I wanted to thank you for the development of this component. And reviewing the example of the storybook I have a question about how to implement a functionality, I would like to change the page that is displayed in the canvas dynamically as it happens when I increase the number in the input of the storybook, but I have not been able to achieve it.

At the moment I have a variable associated to an input that indicates the number of the page and that value I pass it to the page props of the component, but when changing the value of the number the page is not updated on the screen and I was wondering how you achieve it in the storybook, thanks. Maybe I'm overlooking, but I'm out of ideas.

My code is this

<template>
    <input
        id="file-upload"
        name="file-upload"
        type="file"
        class="sr-only"
        @change="handleFile"
    />
    <select name="pages" id="pages" v-model="signPage">
        <option v-for="page in pages" :key="page" :value="page">
            {{ page }}
        </option>
    </select>
    <VuePdf
        :src="file"
        :page="signPage"
        enableTextSelection
        enableAnnotations
    />
</template>

<script>
import { computed, ref } from '@vue/reactivity'
import { VuePdf, createLoadingTask } from 'vue3-pdfjs/esm'

export default {
    components: {
        VuePdf,
    },
    setup() {
        const file = ref('')
        const signPage = ref(1)
        const numOfPages = ref(0)
        const pages = computed(() =>
            [...Array(numOfPages.value + 1).keys()].slice(1)
        )

        const handleFile = (event) => {
            file.value = URL.createObjectURL(event.target.files[0])

            const loadingTask = createLoadingTask(file.value)
            loadingTask.promise.then((pdf) => {
                numOfPages.value = pdf.numPages
            })
        }

        return {
            file,
            signPage,
            pages,
            numOfPages,
            // Methods
            handleFile,
        }
    },
}
</script>
JaavierR commented 2 years ago

I solved it by adding the :key attribute, I don't know if it's the best solution but it does the job. 😁

randolphtellis commented 2 years ago

I solved it by adding the :key attribute, I don't know if it's the best solution but it does the job. 😁

Thanks for your kind words @JaavierR The key attribute is necessary for Vue to track changes, so your solution is perfect.