Electron使用指南 - [11] 添加一个新的信息

1、创建 Store

1.1 编辑 store

编辑 /vue-renderer/src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isShowModal: false
  },

  mutations: {
    setModalVisible(state, show) {
      state.isShowModal = show
    }
  },

  actions: {
    setModalVisible({commit}, show) {
      commit('setModalVisible', show)
    }
  }
})

1.2 引入 store

编辑 /vue-renderer/src/main.js

// ...
import store from './store'
// ...

2、显示添加窗口

编辑 /vue-renderer/src/components/Header.vue:

<template>
  <header>
    <button id="show-modal" @click="setModalVisible(true)">+</button>
    // ...
  </header>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions(['setModalVisible'])
  },
}
</script>

3、完善添加模态组件

编辑 /vue-renderer/src/components/Modal.vue

<template>
  <div id="modal" v-show="isShowModal">
    <input type="text" id="url" :disabled="status" v-model="url" placeholder="输入 URL ...">
    <button id="add-item" :class="{disabled: status}" :disabled="status" @click="addItem">{
   
   {addButtonText}}</button>
    <button id="close-modal" v-show="!status" @click="setModalVisible(false)">取消</button>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  data() {
    return {
      url: '',
      status: false,
      addButtonText: '添加'
    }
  },

  created() {

    // Listen for new item from main process
    ipcRenderer.on('new-item-success', (e, newItem) => {
      console.log(newItem)

      this.status = false
      this.addButtonText = '添加'
      this.url = ''

      this.setModalVisible(false)
    })
  },

  computed: {
    ...mapState(['isShowModal'])
  },

  methods: {
    ...mapActions(['setModalVisible']),

    addItem() {
      if (this.url !== '') {

        // Send new item url to main process
        ipcRenderer.send('new-item', this.url)

        this.status = true
        this.addButtonText = '添加中...'
      }
    }
  }
}
</script>

4、完善主进程 main.js

编辑 /main.js , 在文件代码中的最外层添加 ipcMainnew-item 时间监听,重点是 ipc 通信:

//...

// Modules
const { ipcMain } = require('electron')

// Listen for new item request
ipcMain.on('new-item', (e, itemUrl) => {

  // Get new item and send back to renderer
  setTimeout(() => {
    e.sender.send('new-item-success', 'New item from main process')
  }, 2000)
})

// ...

猜你喜欢

转载自blog.csdn.net/sdasadasds/article/details/110111496