在前期工作的基礎上(Tauri 2.3.1+Leptos 0.7.8開發桌面應用--Sqlite數據庫的寫入、展示和選擇刪除_tauri leptos sqlite 選擇刪除-CSDN博客),實現將選中的數據實時用表格展示出來,效果如下:
1. 后臺invoke調用命令
Tauri后臺lib.rs文件中send_seleted_pdt命令的代碼如下:?
#[tauri::command]
async fn send_selected_pdt(state: tauri::State<'_, DbState>, productlist:Vec<i64>) -> Result<Vec<Pdt>, String> {// 參數名productlist必須與前端定義的結構變量SelectedPdtArgs的鍵值一致let db = &state.db;// 處理空數組的情況if productlist.is_empty() {return Err(String::from("讀取失敗:未提供有效的產品ID"));}// 生成動態占位符(根據數組長度生成 ?, ?, ?)let placeholders = vec!["?"; productlist.len()].join(", ");let query_str = format!("SELECT * FROM products WHERE pdt_id IN ({})",placeholders);// 構建查詢并綁定參數let mut query = sqlx::query_as::<_, Pdt>(&query_str);for id in &productlist {query = query.bind(id);}// 執行讀取操作let query_result = query.fetch_all(db).await.map_err(|e| format!("查詢失敗: {}", e))?;Ok(query_result)}
?命令的返回格式為?Result<Vec<Pdt>, String>,Pdt為結構變量,定義如下:
#[derive(Debug, Serialize, Deserialize, FromRow)]
struct Pdt {pdt_id:i64, //sqlx 會將 SQLite 的 INTEGER 類型映射為 i64(64 位有符號整數)pdt_name:String,pdt_si:f64,pdt_al:f64,pdt_ca:f64,pdt_mg:f64,pdt_fe:f64,pdt_ti:f64,pdt_ka:f64,pdt_na:f64,pdt_mn:f64,pdt_date:String,
}
然后還需對send_selected_pdt命令進行注冊:
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {tauri::Builder::default().plugin(tauri_plugin_opener::init()).invoke_handler(tauri::generate_handler![send_selected_pdt]).menu(|app|{create_menu(app)}).setup(|app| {let main_window = app.get_webview_window("main").unwrap();main_window.on_menu_event(move |window, event| handle_menu_event(window, event));#[cfg(all(desktop))]{let handle = app.handle();tray::create_tray(handle)?; //設置app系統托盤}tauri::async_runtime::block_on(async move {let db = setup_db(&app).await; //setup_db(&app:&mut App)返回讀寫的數據庫對象app.manage(DbState { db }); //通過app.manage(DbState{db})把數據庫對象傳遞給state:tauri::State<'_, DbState>});Ok(())}).run(tauri::generate_context!()).expect("運行Tauri程序的時候出錯!");
}
2. Leptos前端調用并使用表格展示
首先要定義相應的信號,然后在展示的所有數據前面添加復選框,定義復選框選中事件,根據選中數據的Pdt_id列表,實時讀取數據庫的產品數據,并通過表格展示。
信號定義、復選框選中事件函數check_change、讀取數據庫所有數據庫按鈕事件函數receive_pdt_db代碼如下:
#[component]
pub fn AcidInput() -> impl IntoView { //函數返回IntoView類型,即返回view!宏,函數名App()也是主程序view!宏中的組件名(component name)。let (div_content, set_div_content) = signal(view! { <div>{Vec::<View<_>>::new()}</div> });let (selected_items, set_selected_items) = signal::<Vec<i64>>(vec![]);let (selected_pdt_data, set_selected_pdt_data) = signal::<Vec<Pdt>>(vec![]);let (data, set_data) = signal::<Vec<DataPoint>>(vec![]);//處理復選框事件,選中的同時展示在表格中let check_change = move |ev:leptos::ev::Event|{//ev.prevent_default(); spawn_local(async move {let target = event_target::<HtmlInputElement>(&ev);let value_str = target.value(); // 直接獲取 value// 將字符串解析為 i64(需處理可能的錯誤)if let Ok(value) = value_str.parse::<i64>() {set_selected_items.update(|items| {if target.checked() { //target.checked與prop:checked不一樣, 是瀏覽器 DOM 的實時狀態,用于事件處理items.push(value);} else {items.retain(|&x| x != value);}});};//接收讀取的數據log!("選中的數據列表: {:?}", selected_items.get_untracked());if selected_items.get_untracked().len() != 0 {let args = SelectedPdtArgs{productlist:selected_items.get_untracked(),};let args_js = serde_wasm_bindgen::to_value(&args).unwrap(); //參數序列化let pdt_js = invoke("send_selected_pdt", args_js).await;let pdt_vec: Vec<Pdt> = serde_wasm_bindgen::from_value(pdt_js).map_err(|_| JsValue::from("Deserialization error")).unwrap();set_selected_pdt_data.set(pdt_vec);//log!("返回的產品數據: {:?}", selected_pdt_data.get_untracked());}else{set_selected_pdt_data.set(vec![]);}});};let receive_pdt_db = move |ev: SubmitEvent| {ev.prevent_default();spawn_local(async move { //使用Leptos的spawn_local創建一個本地線程(local_thread)Future, 提供一個異步move閉包。let pdt_js = invoke_without_args("send_pdt_db").await;let pdt_vec: Vec<Pdt> = serde_wasm_bindgen::from_value(pdt_js).map_err(|_| JsValue::from("Deserialization error")).unwrap();let mut receive_msg = String::from("讀取數據庫ID序列為:[");// 構建日志消息(注意:pdt_vec 已被消耗,需提前克隆或調整邏輯)let pdt_ids: Vec<i64> = pdt_vec.iter().map(|pdt| pdt.pdt_id).collect();for id in pdt_ids {receive_msg += &format!("{}, ", id);}receive_msg += "]";// 動態生成包裹在 div 中的視圖let div_views = view! {<div>{pdt_vec.into_iter().map(|pdt| {let pdt_id = pdt.pdt_id;view! {<div style="margin:5px;width:1500px;"><inputtype="checkbox"name="items"value=pdt_id.to_string()prop:checked=move || selected_items.get().contains(&pdt_id) //Leptos 的狀態綁定,用于確保界面最終與數據同步。on:change=check_change //用戶操作 → 更新 target.checked → 觸發事件check_change → 更新狀態 → prop:checked 驅動視圖更新。/><span>// 直接使用 Unicode 下標字符"PdtID: " {pdt_id}",產品名稱: " {pdt.pdt_name}",SiO?: " {pdt.pdt_si} "%"",Al?O?: " {pdt.pdt_al} "%"",CaO: " {pdt.pdt_ca} "%"",MgO: " {pdt.pdt_mg} "%"",Fe?O?: " {pdt.pdt_fe} "%"",TiO?: " {pdt.pdt_ti} "%"",K?O: " {pdt.pdt_ka} "%"",Na?O: " {pdt.pdt_na} "%"",MnO?: " {pdt.pdt_mn} "%"",生產日期: " {pdt.pdt_date}</span></div>}}).collect_view()}</div>}; // 關鍵的類型擦除;// 轉換為 View 類型并設置//log!("視圖類型: {:?}", std::any::type_name_of_val(&div_views));set_div_content.set(div_views); set_sql_error.set(receive_msg);});};
};
其中,結構變量Pdt定義如下:
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Pdt {pdt_id:i64,pdt_name:String,pdt_si:f64,pdt_al:f64,pdt_ca:f64,pdt_mg:f64,pdt_fe:f64,pdt_ti:f64,pdt_ka:f64,pdt_na:f64,pdt_mn:f64,pdt_date:String,
}
views!視圖中表格部分內容如下:
<div style="flex: 1;"><PdtTable data=move || selected_pdt_data.get() x_bg_color="red-100" // 對應 --red-100-bgx_text_color="red-800" // 對應 --red-800-text/>
</div>
其中調用了視圖命令PdtTable,具體代碼如下:
#[component]
fn PdtTable<F>(data: F,// 顏色參數(變量)用于設置 CSS 變量 (對應 styles.css 中定義的變量)#[prop(default = "blue-100")] // 對應 --blue-100-bgx_bg_color: &'static str,#[prop(default = "blue-800")] // 對應 --blue-800-textx_text_color: &'static str,#[prop(default = "green-100")] // 對應 --green-100-bgy_bg_color: &'static str,#[prop(default = "green-800")] // 對應 --green-800-texty_text_color: &'static str,
) -> impl IntoView
whereF: Fn() -> Vec<Pdt> + 'static + Send + Sync + Clone,
{view! {<table class="table-container" style="border-collapse: collapse; border: 3px double black;"><thead><tr><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>ID</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>產品名稱</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"SiO2"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"Al2O3"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"CaO"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"MgO"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"Fe2O3"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"TiO2"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"K2O"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"Na2O"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>"MnO2"</th><th class="table-header-cell" style:background-color=move || format!("var(--{}-bg)", x_bg_color) style:color=move || format!("var(--{}-text)", x_text_color)>生產日期</th></tr></thead><tbody>{move || data().into_iter().map(|pdt| view! {<tr><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{pdt.pdt_id}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{pdt.pdt_name}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_si)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_al)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_ca)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_mg)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_fe)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_ti)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_ka)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_na)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{format!("{:.2}", pdt.pdt_mn)}</td><td class="table-data-cell" style:background-color=move || format!("var(--{}-bg)", y_bg_color) style:color=move || format!("var(--{}-text)", y_text_color)>{pdt.pdt_date}</td></tr>}).collect_view()}</tbody></table>}
}
需要強調的是:Leptos 的響應式系統要求組件閉包能在多線程環境中安全傳遞,所以<PdtTable data= move || selected_pdt_data.get() />中閉包要實現線程安全約束(Send + Sync)。具體在程序中為泛型F添加線程安全約束:Send + Sync,為了便于后面克隆,添加Clone約束。
另外在PdtTable中定義了顏色參數(變量)用于設置 CSS 變量,以及用的自定義class,需要在styles.css中添加如下內容:
.table-container {margin-left: auto;margin-right: auto;border-collapse: collapse;border: 3px double #d1d5db;}.table-header-cell {position: sticky;left: 0;background-color: #e5e7eb;padding: 0.5rem 1rem;border: 1px solid #d1d5db;}.table-data-cell {padding: 0.5rem 1rem;min-width: 20px;border: 1px solid #d1d5db;}:root {--blue-100-bg: #dbeafe;--blue-800-text: #1e40af;--red-100-bg: #fee2e2;--red-800-text: #991b1b;--green-100-bg: #dcfce7;--green-800-text: #166534;}
至此,基本就完成了將數據庫選中數據實時用表格顯示出來。
?