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>
相关推荐
前端Hardy18 分钟前
HTML&CSS:3D图片切换效果
前端·javascript
spionbo39 分钟前
Vue 表情包输入组件实现代码及完整开发流程解析
前端·javascript·面试
全宝39 分钟前
✏️Canvas实现环形文字
前端·javascript·canvas
lyc23333339 分钟前
鸿蒙Core File Kit:极简文件管理指南📁
前端
我这里是好的呀40 分钟前
全栈开发个人博客12.嵌套评论设计
前端·全栈
我这里是好的呀41 分钟前
全栈开发个人博客13.AI聊天设计
前端·全栈
金金金__42 分钟前
Element-Plus:popconfirm与tooltip一起使用不生效?
前端·vue.js·element
lyc23333342 分钟前
小L带你看鸿蒙应用升级的数据迁移适配📱
前端
用户26812851066691 小时前
react-pdf(pdfjs-dist)如何兼容老浏览器(chrome 49)
前端