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>
相关推荐
灵感__idea7 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
向葭奔赴♡8 小时前
CSS是什么?—— 网页的“化妆师”
前端·css
黑犬mo8 小时前
在Edge、Chrome浏览器上安装uBlock Origin插件
前端·edge
excel8 小时前
🧩 Vue 3 watch 源码详解(含完整注释)
前端·javascript·vue.js
大前端helloworld8 小时前
前端梳理体系从常问问题去完善-网络篇
前端·面试
excel8 小时前
🌿 一文看懂 Vue 3 的 watch 源码:从原理到流程
前端
繁依Fanyi9 小时前
让工具说话:我在 Inspira Board 里用 AI 把“能用、好用、可复用”落成了日常
前端
weixin_4569042710 小时前
C# 中的回调函数
java·前端·c#
kura_tsuki10 小时前
[Web网页] LAMP 架构与环境搭建
前端·架构
yinuo10 小时前
UniApp+Vue3多分包引入同一 npm 库被重复打包至 vendor 的问题分析与解决
前端