如何在 nuxt(vue) 中使用原始 html 文件?

how to use raw html file in nuxt(vue)?

我想创建一个页面跳转到条带支付页面使用stripe-samples/firebase-subscription-payments。 所以我把它的 html/css/js 文件(在“public”文件夹中)放到我的 nuxt 应用程序的 /static 中。 但是,由于它仅针对静态文件,因此无法使用 vuex 和插件。幸运的是,html 中的标签从 url 中读取 firebase,因此可以使用 firebase。

但是我可以像 .vue 文件一样将原始 html/css/js 文件放入 nuxt/pages 吗?(我试过了但不能..) 我知道最好的方法是将 html/js 文件重写成 vue 文件,但这对我这个初学者来说太难了(另外,我是日本人,我的英语不好,抱歉)。 或者我可以在 /static/files 中使用 npm 包和模块吗? 我已经 google 两天了,无法解决 it.I 真的需要帮助,谢谢!!

这是我的代码: static/public/javascript/app.js


    import firebase from firebase; 
    /*↑ it will be error "Cannot use import statement outside a module".
    but in pages/.vue files and plugins/files, it will work... 
    I also tried "import firebase from '~/plugins/firebase.js'"*/
    
    const STRIPE_PUBLISHABLE_KEY = ....


static/public/index.html

    <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.6/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-functions.js"></script>

    <!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>

    <!-- Add Firebase products that you want to use -->
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>

↑ 它从 url 读取 firebase,但我想使用我安装的 firebase 模块。

您可以在 vue-component-file

中通过 render() 加载 html

nuxt.config.js

    build: {
        extend(config, ctx){
            config.resolve.alias['vue'] = 'vue/dist/vue.common';
        }
    }

在你的 vue 组件文件中

<script>
import myHtml from '~/path/to/your/html/my_html.html';
export default{
    render(h){
         return h({
              template: `<main>${myHtml}</main>`
         });
    }
}
</script>

并且页面将作为组件呈现在您的 vue <router-view/><nuxt/> 中,但请确保您的 my_html.html 中没有 <script> 标签,将render() 中的 js 代码如下所示

<script>
import myHtml from '~/path/to/your/html/my_html.html';
export default{
    render(h){
         return h({
              template: `<main>${myHtml}</main>`,
              created(){
                   console.log('I have been created!')
              },
              mounted(){
                   console.log('I have been mounted!')
              },
              methods: {
                   exampleMethod(){
                        alert('this is an example')
                   }
              }
         });
    }
}
</script>

对此有多种解决方案。

要加载 3rd 方脚本,您可以使用以下解决方案:

根据您要加载的内容,使用 Nuxt 插件也是一种解决方案:https://nuxtjs.org/docs/2.x/directory-structure/plugins/

最后,这里有一个关于如何在 Nuxt 中正确处理 Stripe 的解决方案:

但是 static 不是放置代码的地方。如前所述,这是用于 public 东西,例如网站图标、一些您想与访问者分享的免费 pdf 书籍等.

最近没有在 Nuxt 中使用 firebase,但我希望这些仍然可以帮助弄清楚如何在 Nuxt 中编写它。

最终我将 js / html 代码重写为 vue。基本上就是把js代码复制到mounted()中就完成了,但是由于无法用js操作嵌套的模板标签,所以我用v-if和v-for重写了一部分