0๐
โ
The
#[tauri::command]
is good and all for pure functions, but what happens if we need to preserve some kind of state in the backend, lets say that of a struct instance?
In Tauri youโd do this not with methods, but with State
handled by your Tauri app with the Manager::manage
method (similar to how endpoints in Rust web frameworks like Actix, Axum or Rocket work). Read more about state management in tauri in this section of the guide.
I.e. this could be a setup that works for Tauri using your RandomNumberGenerator
as state while exposing your generate
command to Vue.js:
use tauri::State;
pub struct RandomNumberGenerator
{
used_numbers_repository: Vec<i64>,
}
#[tauri::command]
pub fn generate(rng: State<RandomNumberGenerator>, minimum: i64, maximum: i64) -> String {
todo!();
}
fn main() {
let ng = RandomNumberGenerator::new();
tauri::Builder::default()
.manage(ng) // manage ng as app state
.invoke_handler(tauri::generate_handler![generate])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
In Vue youโd invoke this command like you do in your example:
await invoke("generate", { minimum: minimum.value, maximum: maximum.value })
๐คJonas Fassbender
1๐
After the accepted answer, the code in main.rs became like this:
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::State;
use std::sync::Mutex;
use number_generator::RandomNumberGenerator;
mod number_generator;
#[tauri::command]
fn generate(rng: State<Mutex<RandomNumberGenerator>>, minimum: i64, maximum: i64) -> String {
rng.lock().unwrap().generate(minimum, maximum)
}
#[tauri::command]
fn numbers(rng: State<Mutex<RandomNumberGenerator>>) -> String {
rng.lock().unwrap().used_numbers()
}
fn main() {
let rng = Mutex::new(RandomNumberGenerator::new());
tauri::Builder::default()
.manage(rng)
.invoke_handler(tauri::generate_handler![generate, numbers])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
And added in Generate.vue:
...
const generatedMessage = ref("");
const usedNumbers = ref("");
...
generatedMessage.value = await invoke("generate", { minimum: minimum.value, maximum: maximum.value })
usedNumbers.value = await invoke("numbers")
...
<h4>Used numbers</h4>
<p>{{ usedNumbers }}</p>
๐คVassilisM
Source:stackexchange.com