Tauri+Rust+Vue 跨平台桌面应用简明教程(1)环境创建+系统事件+自定义菜单

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

作者:小牛呼噜噜 | https://xiaoniuhululu.com
计算机内功、JAVA底层、面试相关资料等更多精彩文章在公众号「小牛呼噜噜 」

Tauri简介

Tauri 是一个工具包,可以帮助开发者为主要桌面平台制作应用程序(如 mac,windows,linux 等)。几乎支持现有的任何前端框架(如 react, vue, vite 等),其核心是使用 Rust 编写的。
类似Electron的GUI框架,相比于 Electron,其突出优点就是体积小。我们知道Electron 相当于是打包了一个小型浏览器,体积比较大,还占内存。而 Tauri 开发的应用,前端使用操作系统的 webview,后端集成了 Rust,理论上性能杠杠的,使得打包后的体积相当小。空壳项目Electron 打包的应用大概在 50 M,而 Tauri 只有 4 MB左右。

本文就来尝尝鲜,踩踩坑,顺便和Rust编译器作作斗争!

环境准备

本文只介绍 Windows10下的准备工作,其他环境大家得自行去官网查看https://tauri.app/zh/v1/guides/getting-started/prerequisites

安装Microsoft Visual Studio C++ 生成工具

我们需要安装 Microsoft C++ 生成工具。 其实最简单的方法是下载 Visual Studio 2022 生成工具。 进行安装选择时,请勾选 "C++ 生成工具" 和 Windows 10 SDK。

安装路径自行选择即可

WebView2

Windows 11 已预装了 WebView2

Tauri 需要 WebView2 才能在 Windows 上呈现网页内容,小牛的电脑 还是win10,需要自行去微软网站https://developer.microsoft.com/zh-cn/microsoft-edge/webview2/#download-section下载和运行常青版引导程序
安装脚本会自动为您下载适合您架构的版本。 不过,如果您遇到问题 (特别是 Windows on ARM),您可以自己手动选择正确版本。

Rust

Microsoft Visual Studio C++安装完成后,Rust 所需的 msvc 命令行程序需要手动添加到环境变量中,否则安装 Rust 时 rustup-init 会提示未安装 Microsoft C++ Build Tools,其位于:%Visual Studio 安装位置%\VC\Tools\MSVC\%version%\bin\Hostx64\x64(自行替换其中的 %Visual Studio 安装位置%、%version% 字段)下。

最后需要前往 https://www.rust-lang.org/zh-CN/tools/install 来安装 rustup (Rust 安装程序)。 请注意,为了使更改生效,您必须重新启动终端,在某些情况下需要重新启动 Windows 本身。

https://www.rust-lang.org/zh-CN/learn/get-started下载系统相对应的 Rust 安装程序,一路默认即可。

检查是否安装成功:

C:\windows\system32>rustup -V
rustup 1.24.3 (ce5817a94 2021-05-31)
info: This is the version for the rustup toolchain manager, not the rustc compiler.
info: The currently active `rustc` version is `rustc 1.61.0 (fe5b13d68 2022-05-18)`

创建项目

我们还是走的官网推荐的create-tauri-app项目

cargo install create-tauri-app

cargo create-tauri-app

然后需要选择,npm 包管理器,因为想使用vue-ts

E:\Halo>cargo create-tauri-app

✔ Project name · tauri-app-project-study
✔ Choose your package manager · npm
✔ Choose your UI template · vue-ts

Please follow https://tauri.app/v1/guides/getting-started/prerequisites to install the needed prerequisites, if you haven't already.

Done, Now run:
  cd tauri-app-project-study
  npm install
  npm run tauri dev

最后把 终端提示的命令依次执行完即可

cd tauri-app-project-study
npm install
npm run tauri dev

成功运行项目:

至此,一个新的 Tauri 项目已创建完成,我们使用vscode进行后续的开发

项目结构

项目结构除了多一个src-tauri(这个是rust项目),其他的基本和vue项目结构一样

添加关闭提示

下面我们就简单实现关闭提示的系统事件,来演示一下,tauri 和 rust 配合的效果
打开src/main.rs,我们发现

此处有个爆红,我们只需在根目录下,创建dist文件夹即可让此处不再爆红

#![cfg_attr(
    all(not(debug_assertions), target_os = "windows"),
    windows_subsystem = "windows"
)]

//use tauri::window;

//Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn main() {
    tauri::Builder::default()
		//新增关闭提示的逻辑
        .on_window_event(|event|{
            match event.event() {
                tauri::WindowEvent::CloseRequested { api, .. } =>{
                    //阻止默认关闭
                    api.prevent_close();

                    let window = event.window().clone();
                    tauri::api::dialog::confirm(Some(&event.window()), "关闭应用", "确定关闭当前应用?", move| answer|{
                        if answer {
                            window.close();
                        }
                    })
                },
                _ => {}//todo
            }
        })
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

如果我们最后只写window.close();,编译器会报:unused Result that must be used,this Resultmay be an Err variant, which should be handled就是说这个rust中对于返回值为Result类型的函数,调用方如果没有进行接收,编译期会产生警告

let _result =window.close();//直接接收一下即可,_表示让浏览器忽略未使用的变量

添加自定义菜单

我们就直接用官网的实例,来演示一下了,修改main.rs

use tauri::{Menu, MenuEntry, Submenu, MenuItem};

fn main() {
    tauri::Builder::default()
    	//新增菜单
        .menu(Menu::with_items([
            MenuEntry::Submenu(Submenu::new(
            "File",
            Menu::with_items([
                MenuItem::CloseWindow.into(),
                #[cfg(target_os = "macos")]
                CustomMenuItem::new("hello", "Hello").into(),
            ]),
            )),
        ]))
        .on_window_event(|event|{
            match event.event() {
                tauri::WindowEvent::CloseRequested { api, .. } =>{
                    //阻止默认关闭
                    api.prevent_close();

                    let window = event.window().clone();
                    tauri::api::dialog::confirm(Some(&event.window()), "关闭应用", "确定关闭当前应用?", move| answer|{
                        if answer {
                            let _result =window.close();
                        }
                    })
                },
                _ => {}//todo
            }
        })
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

效果:

本文就先到这里啦,后面我们继续更新tauri+rust更多有意思的特性

参考资料:
https://tauri.app/zh/v1/guides/distribution/windows


本篇文章到这里就结束啦,很感谢你能看到最后,如果觉得文章对你有帮助,别忘记关注我!更多精彩的文章

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue