先上图看效果
主进程监听自定义修改事件
js
ipcMain.on('update-storage', (_, key) => {
webContents.getAllWebContents().map((webContent) => {//获取所有WebContents实例的数组
webContent.send('update-storage', key)//经过预加载脚本向渲染进程发送异步带参消息
})
})
预加载脚本
js
import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
// Custom APIs for renderer
const api = {
//将事件传递给渲染进程,渲染进程通过window访问
onUpdateStorage: (callback: (event: Electron.IpcRendererEvent, ...args: any[]) => void) => {
ipcRenderer.on('update-storage', callback)
}
}
if (process.contextIsolated) {
try {
contextBridge.exposeInMainWorld('electron', electronAPI)
contextBridge.exposeInMainWorld('api', api)
} catch (error) {
console.error(error)
}
} else {
// @ts-ignore (define in dts)
window.electron = electronAPI
// @ts-ignore (define in dts)
window.api = api
}
渲染进程
js
//pinia存储定义修改方法,所有渲染进程引用同一个store
import { defineStore } from 'pinia'
import { reactive } from 'vue'
export const useUserStore = defineStore('user', () => {
const userInfo = reactive({
name: '张三',
age: 16
})
const updateUserInfo = ({ key, value }) => {
userInfo[key] = value
}
return {
userInfo,
updateUserInfo
}
})
html
<template>
<BaseLayout>
<template #header>
<Header minimize="testMinimize" maximize="testMaximize" close="testClose"></Header>
</template>
<el-alert title="test窗口" type="success" />
<div>用户姓名:{{ userStore.userInfo.name }}</div>
<div>用户年龄:{{ userStore.userInfo.age }}</div>
<el-input v-model="keyName" placeholder=""></el-input>
<el-button type="primary" @click="updateUserInfo">修改用户姓名</el-button>
</BaseLayout>
</template>
<script setup lang="ts">
import BaseLayout from '@src/layouts/BaseLayout.vue'
import Header from '@src/layouts/components/Header.vue'
import { useUserStore } from '@src/store/modules'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const keyName = ref('')
const userStore = useUserStore()
const updateUserInfo = () => {
if (keyName.value.trim()) {
const data = {
key: 'name',
value: keyName.value
}
//向主进程发送修改事件
window.electron.ipcRenderer.send('update-storage', JSON.stringify(data))
}
keyName.value = ''
}
//所以渲染进程监听修改事件,调用修改方法
window.electron.ipcRenderer.on('update-storage', (_, data) => {
userStore.updateUserInfo(JSON.parse(data))
ElMessage.success('pinia数据更新了~')
})
</script>
以上采用的方法并没有存储到localstorage里,还可以先存储到localstorage,通过修改事件,pinia直接拿localstorage里面的数据进行赋值(end)