wx-react回應式更改資料重繪界面
微信小程式提供獲取data資料的方式和修改資料的方式分別為this.data.x和this.setData({}),無論是獲取資料或者修改資料都顯得較為繁瑣,且如果x為一個物件或者資料,只修改其值頁面不會自動重繪,需要呼叫this.setData({x: new x})更改資料,重繪界面,所以開發了reactive這個比較小的庫來進行資料的回應式處理,使訪問和修改值的開發效率更高(同時修改多個屬性值建議使用this.setData()方法)
使用前提
-
安裝reactive為依賴
-
npm install wx-react --save
-
yarn add wx-react
-
-
需要正確配置小程式中npm的使用
-
專案使用npm配置,需要在project.config.json中增加如下配置并使用微信開發工具構建npm
"packNpmManually": true,
"packNpmRelationList": [
{
"packageJsonPath": "package.json",
"miniprogramNpmDistDir": "./miniprogram"
}
]
使用方式
-
onLoad()生命周期中呼叫initReactive(this);完成直接this.x代理到this.data.x
-
呼叫reactive方法將物件或陣列轉成代理物件,第一個引數固定this,第二個為需要代理的物件,
Page({ data: { todoList: [] }, onl oad(){ // 步驟一、必須呼叫 initReactive(this); // 步驟二 將目標物件(todoList)轉為代理物件 this.todoList = reactive<TodoItem[]>(this, [{ id: Date.now(), title: 'い 狂奔的蝸牛', finished: false }]); } })
TodoList示例
TS/JS邏輯
import { reactive, initReactive } from 'wx-react';
/*
* @Author: い 狂奔的蝸牛
* @Date: 2021-12-26 13:58:16
* @Description: todoList
*/
interface TodoItem {
id: number;
title: string;
finished: boolean;
}
Page({
data: {
todoList: [], // 待辦事項串列
inputStr: '', // 輸入框輸入值,
options: {}
},
onl oad() {
// 必須執行initReactive(this);
initReactive(this);
// 直接方位或設定值,無需this.data.todoList或this.setData({todoList:[]})
// 將todoList轉為回應式
this.todoList = reactive<TodoItem[]>(this, [{ id: Date.now(), title: 'い 狂奔的蝸牛', finished: false }]);
this.options = reactive<{ title: string }>(this, { title: 'TodoList' });
},
// 輸入事件
handleInput(e: any) {
// 直接訪問data中的屬性
this.inputStr = e.detail.value;
},
// 添加待辦
handleAdd() {
if (!this.inputStr) {
return;
}
// 直接修改值 會自動重繪頁面
this.todoList.push({ id: Date.now(), title: this.data.inputStr, finished: false });
this.inputStr = '';
},
// 洗掉待辦
handleDelete(e: any) {
const index = e.currentTarget.dataset.index * 1;
// 直接修改值 會自動重繪頁面
this.todoList.splice(index, 1);
},
// 完成待辦
handleFinished(e: any) {
const index = e.currentTarget.dataset.index * 1;
// 直接修改值 會自動重繪頁面
this.todoList[index].finished = !this.todoList[index].finished;
},
// 切換title
handleToggleTitle() {
// 直接修改值 會自動重繪頁面
this.options.title = 'TodoList - ' + Date.now().toString().slice(-6);
}
});
效果圖

GitHub專案地址
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394220.html
標籤:其他
上一篇:最新批量搜狗域名添加系結工具
