NuxtJS和VueJS的动态导入

时间:2019-06-17 12:19:33

标签: javascript vue.js asynchronous nuxt.js

我想在nuxtjs中创建动态页面。我的内容存储在content/faq/中的markdown文件中。因此,我需要动态导入以基于param.slug变量导入正确的文件。我该怎么办?

我在_slug.vue中的pages/faq/看起来像这样:

<template>
    <no-ssr>
        <Page :title="title" :subtitle="subtitle" :cover="cover" :images="images" :navigation="navItems != undefined" :navItems="navItems" :footnotes="footnotes">
            <div class="mt-8" v-html="body"/>
        </Page>
    </no-ssr>
</template>

<script>
import Page from '../../components/partials/page'
export default {
    layout: 'static',
    components: {
        Page
    },
    asyncData({ params }) {
        let content = () => import(`../../content/faq/${params.slug}.md`).then(content => {
            return {
                body: content.html,
                cover: content.attributes.cover,
                title: content.attributes.title,
                subtitle: content.attributes.subtitle,
                navigation: content.attributes.nav,
                navItems: content.attributes.navItems,
                footnotes: content.attributes.footnotes,
            }   
        })
    },
    data() {
        return {
            images: [],
            imageDescriptions: []
        }
    },
    created() {
        if (process.client) {
            let parser = new DOMParser();
            let parsedHTML = parser.parseFromString(content.html, 'text/html');
            for (var i = 0; i < parsedHTML.images.length; i++) {
                this.images.push({ 
                    src: parsedHTML.images[i].src, 
                    description: parsedHTML.getElementsByTagName('em')[i].innerText, 
                    alt: parsedHTML.images[i].alt 
                });
            }
            console.log(this.images);
            for (var i = 0; i < parsedHTML.getElementsByTagName('em').length; i++) {
                this.imageDescriptions.push(parsedHTML.getElementsByTagName('em')[i].innerText);
            }
        }
    },
}
</script>

<style>

</style>

当我打开页面localhost:3000/faq/test时收到错误消息:content is not defined但是,当我启动函数created()时,他找不到像body这样的所有变量, covertitle等...

为什么他找不到内容和其他变量?导入是否需要在其他地方进行?

0 个答案:

没有答案