【问题标题】:(Promise/async): "TypeError: Object(...) is not a function" in Vue component(承诺/异步):Vue 组件中的“TypeError: Object(...) is not a function”
【发布时间】:2020-07-11 13:44:42
【问题描述】:

我认为由于 Vue CLI 有大量的node_modules,我可以制作一个能够执行 shell 命令的 Vue 组件(例如ls -l)。

我已通过 vue add electron-builder 添加了 Electron。
我在 mode: process.env.IS_ELECTRON ? 'hash' : 'history', 中有 VueRouter。
我正在使用npm run electron:serve 运行该项目。

这是ShellExec.vue 组件:

<template>
  <div id="wrapper">
    <div class="input_row">
      <input type="text" class="input_text" id="shell" v-model="shell_command" />
      <label class="label_" for="shell">Type Shell Command</label>
    </div>
    <button type="button" class="button" @click="shellExec">Submit !</button>
  </div>
</template>

<script>
import { exec } from "child_process";

export default {
  name: "ShellExec",
  components: {},
  data() {
    return {
      shell_command: ""
    };
  },
  methods: {
    async shell() {
      return new Promise((resolve, reject) => {
        exec(this.shell_command, (err, stdout, stderr) => {
          if (err) {
            reject(err);
          } else {
            resolve({ stdout, stderr });
          }
        });
      });
    },

    async shellExec() {
      let { stdout } = await this.shell();
      for (let line of stdout.split("\n")) {
        console.log(`ls: ${line}`);
      }
    }
  }
};
</script>

<style scoped>
</style>

JS 脚本来自这里:https://*.com/a/31897900/13268871

shell_command 采用我在输入中输入的任何值,因此它似乎可以正常工作。
我正在尝试一个简单的ls -l 命令,但是当我按下Submit ! 按钮时,我收到以下错误:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in v-on handler (Promise/async): "TypeError: Object(...) is not a function"

found in

---> <ShellExec> at src/components/ShellExec.vue
       <App> at src/App.vue
         <Root>
vue.runtime.esm.js?2b0e:1888 TypeError: Object(...) is not a function
    at eval (ShellExec.vue?face:25)
    at new Promise (<anonymous>)
    at _callee$ (ShellExec.vue?face:23)
    at tryCatch (runtime.js?96cf:45)
    at Generator.invoke [as _invoke] (runtime.js?96cf:274)
    at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)
    at asyncGeneratorStep (asyncToGenerator.js?1da1:3)
    at _next (asyncToGenerator.js?1da1:25)
    at eval (asyncToGenerator.js?1da1:32)
    at new Promise (<anonymous>)

【问题讨论】:

  • 您无法在浏览器中运行 shell 命令...但是您可以对服务器进行 ajax 调用,然后在服务器上执行该 shell 命令
  • 意思是我可以用Express JS做一个简单的web服务器,然后用ajax调用来执行shell命令?
  • 简单的快递服务器应该绰绰有余。如果您打算在本地使用它,它将起作用。如果您想与其他人共享此内容,他们将需要您的快速服务器代码才能在他们的计算机上运行 cli 命令。如果是这种情况,您可以使用电子方法 - 将您的 vue 应用程序打包到可以在任何计算机上运行的应用程序中
  • 我想将它部署为 Raspberry Pi 上的 Web 界面。这种情况该怎么办?
  • 对于 Raspberry Pi Web 界面使用 express 和 vue

标签: javascript vue.js


【解决方案1】:

您正在使用npm run serve 在浏览器中进行测试,这当然行不通,因为浏览器不允许这样做。 通过npm run electron:serve 运行有效。无需对 webpack 配置进行任何更改。只需通过import { exec } from 'child_process'; 导入就足够了。

参考:https://github.com/nklayman/vue-cli-plugin-electron-builder/issues/244

【讨论】:

  • 我使用vue add electron-builder 安装了Electron,然后使用npm run electron:serve 运行,我遇到了同样的错误。