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>
相关推荐
01_ice18 分钟前
前端学习css
前端·css·学习
愚公搬代码37 分钟前
【愚公系列】《Web应用安全》010-Repeater模块的使用
前端·安全
Cache技术分享1 小时前
503. Java 反射 - 编写 ServiceFactory 类
前端·后端
赵大仁1 小时前
AI 限流 UX 设计:排队、降级、告知与用户预期管理
前端·ai·限流·用户体验·产品设计
__sjfzllv___1 小时前
在职前端Leader学习/转行 AI Agent -DAY37
前端
用户2181697049301 小时前
Flutter (二十二) GlobalKey
前端
用户2181697049301 小时前
Flutter (二十一) 下拉刷新,加载更多
前端
光影少年2 小时前
react navite 内存泄漏:定时器、监听事件、订阅销毁
前端·javascript·react native·react.js·前端框架
breeze jiang2 小时前
Next.js 16 App Router 实战:从 About、Blog 动态路由到全局 404
开发语言·javascript·ecmascript
小蒜学长2 小时前
vue旅游攻略网站(代码+数据库+LW)
java·数据库·vue.js·spring boot·后端·旅游