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>
相关推荐
feixing_fx11 分钟前
JavaScript 是什么:从浏览器脚本到通用编程语言
开发语言·前端·javascript·前端框架·ecmascript
丘山望岳12 分钟前
【开发工具】 cluade code常用快捷键
前端
小巫编程室22 分钟前
我造了一个 Java 能力包:让 AI 直接调用你的业务代码
java·前端·后端
小y的笔记28 分钟前
JavaScript URL 状态同步
前端·javascript
十有八七28 分钟前
手搓 Agent(五):学会翻书——RAG,先查资料再回答
前端·人工智能·后端
Swot42 分钟前
产品 RAG 知识库与 AI 顾问 设计与实现
前端·后端
htzyl2063 小时前
前端样式-弹窗淡入淡出,为什么你的 `transition` 一直不生效
前端·css·html
Brookty3 小时前
CSS基础知识(二):盒模型、内外边距、外边距折叠与父子元素的布局关系
前端·css
十有八七3 小时前
手搓 Agent(四):长点记性——上下文满了怎么办,怎么记住上一次
前端·人工智能·后端