python EEL + vue3.js 项目中如何把组件中的函数提升为全局函数

eel官方示例中暴露的js函数是全局函数,vue中的自定义函数作用域通常都是组件范围内。要让eel.js调用,需要将其升为全局可用。

一般方法有 app.config.globalProperties 或 mixin等。

main.js

javascript 复制代码
//main.js


import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App);

// 在 Vue 3 中添加全局属性(例如 `$eel`)
app.config.globalProperties.$eel = window.eel;


app.mount('#app');

App.vue

TypeScript 复制代码
<template>
  <img alt="Vue logo" src="./assets/vue.svg"> python eel + Vue3
  <HelloWorld />
</template>

<script>

import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}


</script>

<style>
#app {
  text-align: center;
  margin-top: 60px;
}
</style>

HelloWorld.vue

javascript 复制代码
// HelloWorld.vue

<script setup>

//定义getCurrentInstance().appContext.config.globalProperties
import { ref, onMounted,getCurrentInstance } from 'vue'
const instance = getCurrentInstance();
const globalProperties = instance.appContext.config.globalProperties;

// create a reactive count using ref
const count = ref(0)
const message = ref("Hello World!")
 
const sayHelloByEEL = (x) => {
  globalProperties.$eel.say_hello_py(x + Math.floor(Math.random() * 101).toString())
}

const sayHelloJS = (x) => {
    message.value = 'Say Hello From ' + Math.floor(Math.random() * 101).toString() +x;
}

//使用 globalProperties 暴露sayHelloJS给Python (以say_hello_js为别名)
globalProperties.$eel.expose(sayHelloJS, 'say_hello_js')


onMounted(() => {
  console.log(globalProperties)
})


</script>

<template>

    <p><button type="button" @click="count++">count is: {{ count }}</button></p>

    <p><button @click="sayHelloByEEL('Javascript Button! ')">调用Python函数</button></p>
    <p>{{ message }}</p>
    <p><button @click="sayHelloJS(' JS Button!')">调用JS函数</button></p>

</template>

<style scoped>

</style>
相关推荐
Aotman_29 分钟前
el-input textarea 禁止输入中文字符,@input特殊字符实时替换,光标位置保持不变
前端·javascript·vue.js·前端框架·es6
Nan_Shu_61430 分钟前
Web前端面试题(1)
前端·面试·职场和发展
EveryPossible30 分钟前
选择数据展示
javascript
lypzcgf33 分钟前
Coze源码分析-资源库-创建知识库-前端源码-核心组件
前端·typescript·react·coze·coze源码分析·ai应用平台·agent开发平台
百思可瑞教育1 小时前
在Vue项目中Axios发起请求时的小知识
前端·javascript·vue.js·北京百思教育
患得患失9491 小时前
【个人项目】【前端实用工具】OpenAPI to TypeScript 转换器
前端·javascript·typescript
大前端helloworld2 小时前
前端梳理体系从常问问题去完善-基础篇(html,css,js,ts)
前端·javascript·面试
trsoliu2 小时前
前端基于 TypeScript 使用 Mastra 来开发一个 AI 应用 / AI 代理(Agent)
前端·人工智能
鸡吃丸子2 小时前
前端权限控制:深入理解与实现RBAC模型
前端
Larry_zhang双栖2 小时前
低版本Chrome 内核兼容性问题的优美解决
前端·chrome