📦 Vue 2 Plugin: Automatically manage persistent user preferences
- 🔁 Automatically load and save user preferences (e.g., pagination, filters, chart settings)
- ⚙️ Fully configurable: custom field name, unique ID, context, debounce delay
- 💾 Flexible caching strategy:
localStorage
by default, supports backend APIs - 🧩 Vue Mixin based integration, easy to use and non-intrusive
- 🚀
queryAll
support for preload and performance boost
npm install vue2-user-habit lodash
import { UserHabitManager, createHabitPlugin } from "vue2-user-habit";
const habitManager = new UserHabitManager();
Vue.use(createHabitPlugin(habitManager));
Data is stored in
localStorage
with key formatvue-user-habit:{tag}
.
const habitManager = new UserHabitManager({
strategies: {
async queryOne(ctx) {
return await api.fetchUserPrefs(ctx.tag);
},
async update(ctx, data, previous) {
return await api.updateUserPrefs(ctx.tag, data, previous?.data);
},
async create(ctx, data) {
return await api.createUserPrefs(ctx.tag, data);
},
async queryAll(identity) {
return await api.fetchAllUserPrefs(identity);
},
},
cacheKey: "key",
});
queryAll()
results are deduplicated and cached.get()
uses cache first if available.
export default {
name: "UserListPage",
__habit: {
id: "user-list",
path: "tab1",
field: "prefs",
debounceDelay: 1000,
context: {
userId: "abc123",
},
},
data() {
return {
prefs: { pageSize: 20, filter: {} },
};
},
methods: {
onFilterChanged() {
this.__saveHabitDebounced?.();
},
},
};
Field Name | Type | Default | Description |
---|---|---|---|
id |
string | Component name | Unique habit ID |
path |
string | - | Optional extra path key |
field |
string | habitPrefs |
Data binding field name |
context |
object | {} |
Context passed to strategy |
debounceDelay |
number | 2000 |
Debounce delay in ms |
interface HabitStrategy {
queryOne: (context) => Promise<{ [cacheKey]: string; data: object }>;
update: (context, data) => Promise<any>;
create: (context, data) => Promise<any>;
queryAll: (identity) => Promise<Array<{ [cacheKey]: string; data: object }>>;
}
habitManager.get()
uses internal memory cache first (fromqueryAll
)- If no cache, it falls back to
queryOne()
set()
will decideupdate
orcreate
based oncacheKey
presence
- Habit data fields (e.g.,
prefs
) must be initialized as an object indata()
- Use
this.__habitReady
to wait for preference loading - Automatically save on page exit in
beforeDestroy
; you can also manually trigger saving usingthis.__saveHabitDebounced()
✨ Star, issue or PR are welcome — help make vue2-user-habit
better!