Skip to content

Latest commit

 

History

History
192 lines (177 loc) · 4.79 KB

文档.markdown

File metadata and controls

192 lines (177 loc) · 4.79 KB

python eel + vue 教程

eel打包命令

python -m eel [your_main_script] [your_web_folder]

python -m eel main.py /web

eel如何结合vue开发

一、启动文件配置

import eel
import sys
import platform

"""
原理是:
测试环境:
1、测试环境设置启动页面为vue的测试服务端口,develop=True
2、将端口和vue的public/index.html 中的eel.js绑定/ develop=False
生产环境:
和正常的一样使用
"""
def start_eel(develop):
    """Start Eel with either production or development configuration."""
    if develop:
        directory = 'src'
        app = 'chrome'
        page = {'port': 9100}
        eel_kwargs = dict(
            mode=app,
            host="localhost",
            port=9000,
        )
    else:
        directory = 'web'
        app = 'chrome'
        page = 'index.html'
        eel_kwargs = dict(
            mode=app,
            port=0,
            size=(1280, 800),
        )
    eel.init(directory)
    try:
        eel.start(page, **eel_kwargs)
    except EnvironmentError:
        # If Chrome isn't found, fallback to Microsoft Edge on Win10 or greater
        if sys.platform in ["win32", "win64"] and int(platform.release()) >= 10:
            eel.start(page, mode="edge", **eel_kwargs)
        else:
            raise

if __name__ == "__main__":
    print("Opening python...")
    start_eel(False)

二、VUE 的相关配置

1、vite 生成的项目根目录创建vite.config.ts 2、vite.config.ts中配置: (将导出目录设置到web中,否则可能eel无法调用web中js)

import { defineConfig } from 'vite'
import vuePlugin from '@vitejs/plugin-vue'
import { join } from 'path'
import { createHtmlPlugin } from 'vite-plugin-html'
// https://vitejs.dev/config/
function resolve(dir: string) {
  return join(__dirname, dir)
}

export default defineConfig({
  mode: process.env.NODE_ENV,
  server: {
    host: 'localhost',
    port: 9100,
  },
  resolve: {
    alias: {
      // 如果报错__dirname找不到,需要安装node,执行npm install @types/node --save-dev
      '@': resolve('src'),
      '@hooks': resolve('src/hooks'),
      '@assets': resolve('src/assets'),
      '@components': resolve('src/components'),
      '@images': resolve('src/assets/images'),
      '@views': resolve('src/views'),
      '@store': resolve('src/store'),
    },
    extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.html'],
  },
  build: {
    outDir: resolve('/web'),
    emptyOutDir: true,
    target: 'esnext',
    minify: 'esbuild',
  },
  plugins: [
    vuePlugin({
      script: {
        refSugar: true,
      },
    }),
    createHtmlPlugin({
      minify: true,
      /**
       * 需要注入 index.html ejs 模版的数据
       */
      inject: {
        data: {
          title: 'index',
          injectScript:
            process.env.NODE_ENV === 'production'
              ? `<script src="/eel.js"></script>`
              : `<script src="http://localhost:9000/eel.js"></script><script>window.eel.set_host("ws://localhost:9000");</script>`,
        },
      },
    }),
  ],
  optimizeDeps: {},
})

3、public/index.html中插入

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= title %></title>
    <%- injectScript %>
</head>
  <body>
    <noscript>
    <strong>We're sorry but <%= title %> doesn't work properly without JavaScript enabled.
        Please enable it to continue.</strong>
</noscript>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>

<script>
    // 将js中的函数暴露给python,这个貌似不怎么需要用
    eel.expose(js_fun);
    function js_fun(msg) {
        alert('你好啊' + msg)
    }
</script>
</html>

三、使用方法参考eel的使用教程

##JS端调用python方法 1、python 中声明方法,通过@eel.expose注解导出

import eel

# 导出方法到javascript
@eel.expose  
def say_hello_py(x):
    """Print message from JavaScript on app initialization, then call a JS function."""
    print("Hello from %s" % x)
    eel.say_hello_js("Python {from within say_hello_py()}!")
// 调用方法 windows.eel.[方法名]
 windows.eel.say_hello_py("你好啊")

##Python端调用JS方法

    // 声明方法
    function sayHelloJS(x) {
        console.log("Hello from " + x);
    }
        
    //导出方法到python
    // WARN: must use window.eel to keep parse-able eel.expose{...}
    window.eel.expose(sayHelloJS, "say_hello_js");
 import eel
# 调用js方法 eel.[js方法名]
# 调用方法必须在eel.init()方法后面执行

 eel.say_hello_js(
        "Python World!"
    )