electron-vue-运行cmd命令

在electron中调用cmd命令,可以通过node-cmd来实现:
安装node-cmd模块

npm install node-cmd

安装完成后,可以通过两种方式来调用

1)将node-cmd定义为插件,通过插件进行调用,如果应用有多个页面需要调用到cmd,可以通过插件方式

在renderer下新建plugins/cmd/index.js

/**
 * 自定义cmd插件
 * @author LiQun
 * @date 2019/4/14
 */
const cmdPlugin = {
  install (Vue) {
    Vue.prototype.$cmd = require('node-cmd')
  }
}

export default cmdPlugin

在main.js中添加插件

import cmd from './plugins/cmd/index'

Vue.use(cmd)

需要调用的页面

<template>
  <div style="margin-top: 50px;">
    <button @click="testCmd">testCmd</button>
  </div>
</template>

<script>
  /**
   * 测试页面
   * @author LiQun
   * @date 2019/3/25
   */
  export default {
    name: 'home',
    data () {
      return {}
    },
    methods: {
      testCmd () {
        this.$cmd.get(
          `
            ls
          `,
          function (err, data, stderr) {
            console.log(stderr)
            if (!err) {
              console.log('the node-cmd cloned dir contains these files :\n\n', data)
            } else {
              console.log('error', err)
            }
          }
        )
      }
    },
    computed: {},
    mounted () {
      console.log(this.$electron)
    }
  }
</script>

<style scoped lang="scss">
</style>

2)页面直接调用,html部分相同,不再额外列举:

<script>
  const cmd = require('node-cmd')
  /**
   * 测试页面
   * @author LiQun
   * @date 2019/3/25
   */
  export default {
    name: 'home',
    data () {
      return {}
    },
    methods: {
      testCmd () {
        cmd.get(
          `
            ls
          `,
          function (err, data, stderr) {
            console.log(stderr)
            if (!err) {
              console.log('the node-cmd cloned dir contains these files :\n\n', data)
            } else {
              console.log('error', err)
            }
          }
        )
      }
    },
    computed: {},
    mounted () {
      console.log(this.$electron)
    }
  }
</script>

结果:


结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。