I use some (client-side) Vue in my projects. Personally, I don't like to go crazy with it, I just put some stuff in the Vue architecture when I can use it. This project is now built with TypeScript for better type safety and developer experience.
site.ts is the main entry point and uses ES6 imports. It imports utility functions from globals/_functions.ts, variables from partials/_variables.ts, and initializes the Vue app from partials/_vue.ts.
The TypeScript files in the src/ts/ folder are compiled to JavaScript in the js/min/ folder. The compiled code uses ES modules and is loaded with type="module" in the HTML.
src/ts/site.ts- Main entry pointsrc/ts/globals/_functions.ts- Utility functionssrc/ts/partials/_variables.ts- Site-wide variablessrc/ts/partials/_vue.ts- Vue app initialization
To use functions from another file, simply import them:
import { randomNumber, addCommas } from "./globals/_functions.js";
const num = randomNumber(1, 100);
const formatted = addCommas(num);I'll walk through a couple of the generic utility functions here.
Generates a random (whole) number between the minimum and maximum
example:
randomNumber(1, 100);Takes any large number and formats it like 10,232,021
example:
addCommas(10232021);Calculates the percentage of part within total
example:
percentOf(37, 14);If you have a simple array, this will pluck a random selection from that array.
example:
let hello = randomFrom(WelcomeMessages);Have a simple array? Or an array of objects? Use this to shuffle the order of all of them.
example:
shuffle(deckOfCards);Returns the index of an item if it's in the array, if it isn't, returns null
example:
if (findInArray(people, "Lemon") !== null) {
// do stuff.
}Want to remove a particular string (or object) from an array? Do it like this.
example:
removeFromArray(listOfNames, "Lemon");This is meant to work with Google Analytics. The function will send an event to Google with the variables specified. label and value are optional. Also, if you have a value, value must be a number (strings will cause an error in GA).
example:
sendEvent("Merch", "Merch Bought", "XL Shirt", 25);If you want to use Matomo instead of GA (which is a good choice), look here for similar syntax.