【问题标题】:How to import extrenal library on mounted hook in Nuxt Js?如何在 Nuxt Js 的挂载钩子上导入外部库?
【发布时间】:2020-02-14 05:51:59
【问题描述】:

我在我的 nuxt js 项目中使用 conversation form 包。我发现自定义 component from github 使用了这个包。

组件代码:

<template>
  <form id="my-form-element" cf-form></form>
</template>

<script>
import * as cf from 'conversational-form'

export default {
  mounted: function() {
    this.setupForm()
  },
  methods: {
    setupForm: function() {
      const formFields = [
        {
          tag: 'input',
          type: 'text',
          name: 'firstname',
          'cf-questions': 'What is your firstname?'
        },
        {
          tag: 'input',
          type: 'text',
          name: 'lastname',
          'cf-questions': 'What is your lastname?'
        }
      ]

      this.cf = cf.startTheConversation({
        options: {
          submitCallback: this.submitCallback
        },
        tags: formFields
      })
      this.$el.appendChild(this.cf.formEl)
    },
    submitCallback: function() {
      const formDataSerialized = this.cf.getFormData(true)
      console.log('Formdata, obj:', formDataSerialized)
      this.cf.addRobotChatResponse(
        'You are done. Check the dev console for form data output.'
      )
    }
  }
}
</script>

现在当我使用这个组件时得到错误消息:

没有定义窗口

作为这个错误的解决方案推荐这个answer from stackowerflow

看到这个答案后,我更改了组件代码。

变化:

1.Removedimport * as cf from 'conversational-form'

2.将mounted()钩子内容替换为:

var cf = require('conversational-form')
this.setupForm()

修改后错误已修复,但包无法正常工作。当在方法内部调用这个库时,this.cf nuxt js 找不到cf var。我该如何解决这个问题?

你也可以在vue jshere看到这个包的现场演示

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js


    【解决方案1】:

    这是一种罕见的情况,您可能需要使用&lt;client-only&gt; 标记。如果您使用的是早于 2.9.0 的版本,则为 &lt;no-ssr&gt;。找到的文档here

    例子:

    <template>
      <client-only>
        <form id="my-form-element" cf-form></form>
      </client-only>
    </template>
    <script>
    import * as cf from 'conversational-form'
    
    export default { ... }
    </script>
    

    这指示 Nuxt 只渲染组件客户端,其中定义了窗口。

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      相关资源
      最近更新 更多