0
# Logical Operations
1
2
Reactive logical operations including AND, OR, and NOT with support for multiple arguments and aliased exports. These functions provide reactive Boolean logic that automatically updates when input values change.
3
4
## Capabilities
5
6
### logicAnd
7
8
Reactive AND operation that returns true only when all input values are truthy.
9
10
```typescript { .api }
11
/**
12
* Reactive AND operation on multiple values
13
* @param args - Multiple reactive values to AND together
14
* @returns ComputedRef<boolean> that updates when any input changes
15
*/
16
function logicAnd(...args: MaybeRefOrGetter<any>[]): ComputedRef<boolean>;
17
18
// Alias for shorter usage
19
const and: typeof logicAnd;
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import { ref } from "vue";
26
import { logicAnd, and } from "@vueuse/math";
27
28
// Basic AND operation
29
const condition1 = ref(true);
30
const condition2 = ref(false);
31
const condition3 = ref(true);
32
33
const result = logicAnd(condition1, condition2, condition3);
34
console.log(result.value); // false (one condition is false)
35
36
condition2.value = true;
37
console.log(result.value); // true (all conditions are now true)
38
39
// Using the alias
40
const shortResult = and(condition1, condition2);
41
console.log(shortResult.value); // true
42
43
// Works with any truthy/falsy values
44
const name = ref("");
45
const email = ref("user@example.com");
46
const age = ref(25);
47
48
const isValidUser = logicAnd(name, email, age);
49
console.log(isValidUser.value); // false (empty name is falsy)
50
51
name.value = "John";
52
console.log(isValidUser.value); // true (all values are truthy)
53
54
// Mixed with computed values
55
const hasPermissions = computed(() => user.role === 'admin');
56
const isAuthenticated = ref(true);
57
const canAccess = logicAnd(hasPermissions, isAuthenticated);
58
```
59
60
### logicOr
61
62
Reactive OR operation that returns true when at least one input value is truthy.
63
64
```typescript { .api }
65
/**
66
* Reactive OR operation on multiple values
67
* @param args - Multiple reactive values to OR together
68
* @returns ComputedRef<boolean> that updates when any input changes
69
*/
70
function logicOr(...args: MaybeRefOrGetter<any>[]): ComputedRef<boolean>;
71
72
// Alias for shorter usage
73
const or: typeof logicOr;
74
```
75
76
**Usage Examples:**
77
78
```typescript
79
import { ref } from "vue";
80
import { logicOr, or } from "@vueuse/math";
81
82
// Basic OR operation
83
const hasEmail = ref(false);
84
const hasPhone = ref(false);
85
const hasSocial = ref(true);
86
87
const hasContact = logicOr(hasEmail, hasPhone, hasSocial);
88
console.log(hasContact.value); // true (at least one contact method)
89
90
hasSocial.value = false;
91
console.log(hasContact.value); // false (no contact methods)
92
93
hasPhone.value = true;
94
console.log(hasContact.value); // true (phone is available)
95
96
// Using the alias
97
const quickCheck = or(hasEmail, hasPhone);
98
99
// Permission checking
100
const isOwner = ref(false);
101
const isAdmin = ref(false);
102
const isModerator = ref(true);
103
104
const canEdit = logicOr(isOwner, isAdmin, isModerator);
105
console.log(canEdit.value); // true (moderator can edit)
106
107
// Fallback values
108
const primaryApi = ref("");
109
const secondaryApi = ref("");
110
const localCache = ref("cached-data");
111
112
const hasDataSource = logicOr(primaryApi, secondaryApi, localCache);
113
console.log(hasDataSource.value); // true (local cache available)
114
```
115
116
### logicNot
117
118
Reactive NOT operation that inverts the truthiness of a single value.
119
120
```typescript { .api }
121
/**
122
* Reactive NOT operation on a value
123
* @param v - Reactive value to invert
124
* @returns ComputedRef<boolean> containing the inverted boolean value
125
*/
126
function logicNot(v: MaybeRefOrGetter<any>): ComputedRef<boolean>;
127
128
// Alias for shorter usage
129
const not: typeof logicNot;
130
```
131
132
**Usage Examples:**
133
134
```typescript
135
import { ref } from "vue";
136
import { logicNot, not } from "@vueuse/math";
137
138
// Basic NOT operation
139
const isLoading = ref(true);
140
const isReady = logicNot(isLoading);
141
142
console.log(isReady.value); // false (not ready while loading)
143
144
isLoading.value = false;
145
console.log(isReady.value); // true (ready when not loading)
146
147
// Using the alias
148
const isNotEmpty = not(ref(""));
149
console.log(isNotEmpty.value); // false (empty string is falsy)
150
151
// Toggle pattern
152
const isVisible = ref(false);
153
const isHidden = logicNot(isVisible);
154
155
// UI state management
156
const hasErrors = ref(false);
157
const isValid = logicNot(hasErrors);
158
const canSubmit = computed(() => isValid.value && form.isDirty);
159
160
// Inverting complex conditions
161
const isOffline = computed(() => !navigator.onLine);
162
const isOnline = logicNot(isOffline);
163
```
164
165
## Advanced Usage Patterns
166
167
### Complex Boolean Logic
168
169
```typescript
170
import { ref, computed } from "vue";
171
import { logicAnd, logicOr, logicNot } from "@vueuse/math";
172
173
// User authentication and authorization
174
const isLoggedIn = ref(false);
175
const hasValidToken = ref(false);
176
const isEmailVerified = ref(false);
177
const isBanned = ref(false);
178
179
// Complex authentication state
180
const isAuthenticated = logicAnd(isLoggedIn, hasValidToken);
181
const isVerified = logicAnd(isAuthenticated, isEmailVerified);
182
const isNotBanned = logicNot(isBanned);
183
const canAccess = logicAnd(isVerified, isNotBanned);
184
185
console.log(canAccess.value); // false (not logged in)
186
187
// Simulate login flow
188
isLoggedIn.value = true;
189
hasValidToken.value = true;
190
isEmailVerified.value = true;
191
console.log(canAccess.value); // true (all conditions met)
192
193
// Ban user
194
isBanned.value = true;
195
console.log(canAccess.value); // false (user is banned)
196
```
197
198
### Form Validation
199
200
```typescript
201
import { ref, computed } from "vue";
202
import { logicAnd, logicOr, logicNot } from "@vueuse/math";
203
204
// Form fields
205
const username = ref("");
206
const email = ref("");
207
const password = ref("");
208
const confirmPassword = ref("");
209
const agreeToTerms = ref(false);
210
211
// Field validations
212
const isUsernameValid = computed(() => username.value.length >= 3);
213
const isEmailValid = computed(() => /\S+@\S+\.\S+/.test(email.value));
214
const isPasswordValid = computed(() => password.value.length >= 8);
215
const isPasswordMatch = computed(() => password.value === confirmPassword.value);
216
217
// Combined validations using logical operations
218
const areFieldsValid = logicAnd(
219
isUsernameValid,
220
isEmailValid,
221
isPasswordValid,
222
isPasswordMatch
223
);
224
225
const hasRequiredConsent = logicAnd(agreeToTerms);
226
const canSubmit = logicAnd(areFieldsValid, hasRequiredConsent);
227
228
// Error states
229
const hasUsernameError = logicAnd(
230
computed(() => username.value.length > 0), // Only show error if user has typed
231
logicNot(isUsernameValid)
232
);
233
234
const hasEmailError = logicAnd(
235
computed(() => email.value.length > 0),
236
logicNot(isEmailValid)
237
);
238
239
// Watch for changes
240
watch(canSubmit, (isValid) => {
241
console.log(`Form ${isValid ? 'can' : 'cannot'} be submitted`);
242
});
243
244
// Test the form
245
username.value = "john";
246
email.value = "john@example.com";
247
password.value = "secretpassword";
248
confirmPassword.value = "secretpassword";
249
agreeToTerms.value = true;
250
251
console.log(canSubmit.value); // true
252
```
253
254
### Feature Flags and Conditional Logic
255
256
```typescript
257
import { ref, computed } from "vue";
258
import { logicAnd, logicOr, logicNot } from "@vueuse/math";
259
260
// Feature flags
261
const enableBetaFeatures = ref(false);
262
const enablePremiumFeatures = ref(false);
263
const isDebugMode = ref(true);
264
265
// User properties
266
const isPremiumUser = ref(false);
267
const isBetaTester = ref(true);
268
const isDeveloper = ref(false);
269
270
// Feature availability logic
271
const canUseBetaFeatures = logicAnd(enableBetaFeatures, isBetaTester);
272
const canUsePremiumFeatures = logicOr(
273
logicAnd(enablePremiumFeatures, isPremiumUser),
274
isDeveloper // Developers get access to everything
275
);
276
277
const showDebugInfo = logicOr(isDebugMode, isDeveloper);
278
const showAdvancedSettings = logicOr(canUsePremiumFeatures, canUseBetaFeatures);
279
280
// Environment-based features
281
const isProduction = computed(() => process.env.NODE_ENV === 'production');
282
const isDevelopment = logicNot(isProduction);
283
const enableAnalytics = logicAnd(isProduction, logicNot(isDeveloper));
284
285
console.log({
286
canUseBeta: canUseBetaFeatures.value,
287
canUsePremium: canUsePremiumFeatures.value,
288
showDebug: showDebugInfo.value,
289
showAdvanced: showAdvancedSettings.value,
290
enableAnalytics: enableAnalytics.value
291
});
292
293
// Simulate feature toggle
294
enableBetaFeatures.value = true;
295
console.log(`Beta features now ${canUseBetaFeatures.value ? 'enabled' : 'disabled'}`);
296
```
297
298
### State Machine Logic
299
300
```typescript
301
import { ref, computed } from "vue";
302
import { logicAnd, logicOr, logicNot } from "@vueuse/math";
303
304
// Application states
305
const isIdle = ref(true);
306
const isLoading = ref(false);
307
const hasData = ref(false);
308
const hasError = ref(false);
309
310
// State transitions
311
const canStartLoading = logicAnd(isIdle, logicNot(isLoading));
312
const canShowData = logicAnd(hasData, logicNot(hasError), logicNot(isLoading));
313
const canRetry = logicOr(hasError, logicAnd(logicNot(hasData), logicNot(isLoading)));
314
const shouldShowSpinner = logicAnd(isLoading, logicNot(hasError));
315
316
// State machine functions
317
function startLoading() {
318
if (canStartLoading.value) {
319
isIdle.value = false;
320
isLoading.value = true;
321
hasError.value = false;
322
}
323
}
324
325
function finishLoading(success: boolean, data?: any) {
326
isLoading.value = false;
327
if (success) {
328
hasData.value = !!data;
329
hasError.value = false;
330
isIdle.value = false;
331
} else {
332
hasError.value = true;
333
hasData.value = false;
334
isIdle.value = true;
335
}
336
}
337
338
function reset() {
339
isIdle.value = true;
340
isLoading.value = false;
341
hasData.value = false;
342
hasError.value = false;
343
}
344
345
// Usage
346
console.log(`Can start loading: ${canStartLoading.value}`); // true
347
startLoading();
348
console.log(`Should show spinner: ${shouldShowSpinner.value}`); // true
349
350
setTimeout(() => {
351
finishLoading(true, { users: [] });
352
console.log(`Can show data: ${canShowData.value}`); // true
353
}, 1000);
354
```