move skills out of this repo

This commit is contained in:
Mark Eaton committed 2026-11-11 14:32:53 -05:00
1 parent bf5a89f5a2
commit 1782c29b95
4 files changed
-1071

No files matched your search

-206
View File
@@ -1,206 +0,0 @@
# Flask Security Audit
Perform a security audit of this Flask (or Quart) application. Work through each section below, report findings, and fix issues. At the end, provide a summary with a letter grade for each area.
## Instructions
- Audit the project against every section below.
- For each section, report: what is already correct, what needs fixing, and what is not applicable.
- Fix all issues you find. If a fix would be disruptive or ambiguous, describe the fix and ask before applying it.
- At the end, produce a **Security Audit Summary** table with a letter grade (A-F) for each section.
---
## 1. Resource Limits (DoS Prevention)
Verify these Flask config values are set explicitly (not left at defaults):
```python
app.config['MAX_CONTENT_LENGTH'] = <appropriate_limit> # e.g. 16 * 1024 * 1024 for 16MB
app.config['MAX_FORM_MEMORY_SIZE'] = <appropriate_limit> # default 500kB
app.config['MAX_FORM_PARTS'] = <appropriate_limit> # default 1000
```
- `MAX_CONTENT_LENGTH` has no default — it **must** be set.
- Consider the app's actual needs when choosing values.
---
## 2. Cross-Site Scripting (XSS)
Check for these common XSS pitfalls:
- **Unquoted HTML attributes** — all template attributes must be quoted: `<input value="{{ value }}">`, never `<input value={{ value }}>`.
- **`Markup()` on user input** — never call `Markup()` or `|safe` on user-submitted data.
- **HTML generated outside Jinja** — any HTML built in Python code must be escaped.
- **Uploaded files served as HTML** — uploaded files should be served with `Content-Disposition: attachment` or stored with validated content types.
- **`javascript:` URIs** — if any `href` or `src` attribute uses a user-controlled value, validate that it starts with `http://`, `https://`, or `/`. Enforce via CSP as well.
---
## 3. Cross-Site Request Forgery (CSRF)
Flask has no built-in CSRF protection. Verify that:
- A CSRF library is in use (e.g. Flask-WTF's `CSRFProtect`, or equivalent).
- All state-changing forms include CSRF tokens.
- AJAX state-changing requests include CSRF tokens in headers.
- If no CSRF protection exists, add it using Flask-WTF:
```python
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
```
```html
<form method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
...
</form>
```
---
## 4. Security Headers
Check that the following response headers are set. Recommend Flask-Talisman if headers are missing or manually managed:
| Header | Required Value |
|--------|---------------|
| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` |
| `Content-Security-Policy` | See Section 5 below |
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `DENY` or `SAMEORIGIN` |
If Flask-Talisman is not in use, suggest adding it:
```python
from flask_talisman import Talisman
Talisman(app, content_security_policy=csp)
```
---
## 5. Content Security Policy (CSP)
Audit the CSP and make it as restrictive as possible. Apply these principles:
- Start from `default-src 'self'` and only open directives that the app actually needs.
- **Never allow** `unsafe-inline` for `script-src` unless absolutely unavoidable. Prefer nonces or hashes.
- **Never allow** `unsafe-eval` for `script-src`.
- Avoid wildcard (`*`) origins — list specific domains.
- Set `form-action 'self'` to prevent form hijacking.
- Set `frame-ancestors 'none'` (or `'self'`) to prevent clickjacking (replaces X-Frame-Options).
- Set `base-uri 'self'` to prevent base tag hijacking.
- Set `object-src 'none'` to block plugins.
Provide:
1. The current CSP (or note its absence).
2. A recommended CSP with explanations for each directive.
3. A letter grade (A-F) assessing how restrictive the CSP is.
---
## 6. Cookie and Session Security
Verify these session/cookie configuration values:
```python
app.config.update(
SESSION_COOKIE_SECURE=True, # cookies sent over HTTPS only
SESSION_COOKIE_HTTPONLY=True, # no JavaScript access to session cookie
SESSION_COOKIE_SAMESITE='Lax', # CSRF protection for cookies
PERMANENT_SESSION_LIFETIME=600, # session timeout in seconds
)
```
Also check:
- Any manually set cookies (`response.set_cookie(...)`) should use `secure=True`, `httponly=True`, and `samesite='Lax'`.
- Sessions are cleared on login (`session.clear()` before setting new session data).
- `SECRET_KEY` is cryptographically random and not hardcoded (see Section 7).
---
## 7. Secrets Management
Verify that:
- **No secrets are hardcoded** in source files. Search for: `SECRET_KEY`, `PASSWORD`, `API_KEY`, `TOKEN`, database URIs with credentials, and similar patterns.
- All secrets are loaded from environment variables.
- A `.env` file exists for local development, and `.env` is listed in `.gitignore`.
- Use `python-dotenv` to load the `.env` file:
```python
from dotenv import load_dotenv
load_dotenv()
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
```
- Create `.gitignore` if it does not exist. Ensure `.env` is in it.
- If a `.env.example` file does not exist, create one with placeholder values (never real secrets).
---
## 8. CORS Configuration
If CORS is configured (e.g. via Flask-CORS), review and explain:
- Which origins are allowed. Flag `*` (allow-all) as a problem unless this is a fully public API.
- Which methods and headers are allowed.
- Whether `supports_credentials=True` is set — this is dangerous with broad origins.
- If CORS is not needed, confirm it is not enabled.
---
## 9. Host Header Validation
Check that trusted hosts are configured to prevent host header poisoning:
```python
app.config['TRUSTED_HOSTS'] = ['example.com', 'www.example.com']
```
If the app runs behind a reverse proxy, verify `ProxyFix` is configured correctly:
```python
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
```
---
## 10. Additional Checks
- **Debug mode**: Verify `app.debug` is `False` and `FLASK_DEBUG` is not set to `1` in production config.
- **JSON security**: If the app returns JSON arrays at top level, confirm this is intentional.
- **File uploads**: If file uploads exist, verify filenames are sanitized with `werkzeug.utils.secure_filename()`.
- **SQL injection**: If raw SQL is used, verify parameterized queries. Flag any string concatenation/formatting in SQL.
- **Dependency vulnerabilities**: Run `pip audit` or `safety check` if available and report results.
---
## Security Audit Summary
After completing all sections, produce a summary in this format:
| Section | Grade | Notes |
|---------|-------|-------|
| 1. Resource Limits | ? | |
| 2. XSS Prevention | ? | |
| 3. CSRF Protection | ? | |
| 4. Security Headers | ? | |
| 5. Content Security Policy | ? | |
| 6. Cookie/Session Security | ? | |
| 7. Secrets Management | ? | |
| 8. CORS Configuration | ? | |
| 9. Host Header Validation | ? | |
| 10. Additional Checks | ? | |
| **Overall** | **?** | |
Grading scale:
- **A**: Best practices fully implemented
- **B**: Mostly good, minor improvements possible
- **C**: Functional but missing important protections
- **D**: Significant security gaps
- **F**: Critical vulnerabilities present
-276
View File
@@ -1,276 +0,0 @@
# Pytest TDD Workflow — Advanced
This skill extends the core PYTEST skill with advanced testing techniques. Use when the basic red-green-refactor cycle is comfortable and you need fixtures, parametrize, mocking, or Flask/Quart test patterns.
**All rules from the core PYTEST skill still apply** — always follow red-green-refactor, always write the test first.
## Instructions
- Follow the red-green-refactor cycle for every piece of functionality.
- Use the techniques below when they genuinely simplify or improve tests.
- Run tests after every change.
---
## 1. Fixtures
Use fixtures for setup code that multiple tests share.
### Basic fixture
```python
# tests/conftest.py
import pytest
@pytest.fixture
def sample_user():
return User(name="alice", email="alice@example.com")
```
```python
# tests/test_models.py
def test_user_display_name(sample_user):
assert sample_user.display_name == "alice"
```
### Yield fixtures for setup/teardown
```python
@pytest.fixture
def db_session():
session = create_session()
yield session
session.rollback()
session.close()
```
### Fixture scope
| Scope | Lifetime | Use when |
|-------|----------|----------|
| `"function"` (default) | Each test | Most cases — tests stay isolated |
| `"class"` | Each test class | Grouping related tests with shared setup |
| `"module"` | Each test file | Expensive setup shared across a file |
| `"session"` | Entire test run | Very expensive one-time setup (e.g. database creation) |
Prefer `function` scope. Only widen scope when setup is genuinely expensive and tests do not mutate shared state.
### conftest.py organization
- `tests/conftest.py` — fixtures used across the entire test suite
- `tests/api/conftest.py` — fixtures specific to API tests
- Fixtures in a `conftest.py` are available to all tests in that directory and below
---
## 2. Flask/Quart Test Patterns
### App factory fixture
```python
# tests/conftest.py
import pytest
from myapp import create_app
@pytest.fixture
def app():
app = create_app({
"TESTING": True,
"SECRET_KEY": "test-secret-key",
})
yield app
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def runner(app):
return app.test_cli_runner()
```
### Testing routes
```python
def test_homepage_returns_200(client):
response = client.get("/")
assert response.status_code == 200
def test_homepage_contains_title(client):
response = client.get("/")
assert b"Welcome" in response.data
```
### Testing POST requests and forms
```python
def test_login_with_valid_credentials(client):
response = client.post("/login", data={
"username": "alice",
"password": "correct-password",
}, follow_redirects=True)
assert response.status_code == 200
```
### Testing JSON APIs
```python
def test_api_returns_user_list(client):
response = client.get("/api/users")
assert response.status_code == 200
data = response.get_json()
assert isinstance(data, list)
```
### Testing with application context
```python
def test_db_query_within_app_context(app):
with app.app_context():
users = User.query.all()
assert len(users) >= 0
```
### Testing with request context
```python
def test_url_generation(app):
with app.test_request_context():
assert url_for("index") == "/"
```
### Quart async tests
For Quart applications, use `pytest-asyncio`:
```python
import pytest
@pytest.fixture
def app():
app = create_app({"TESTING": True})
return app
@pytest.fixture
def client(app):
return app.test_client()
@pytest.mark.asyncio
async def test_homepage(client):
response = await client.get("/")
assert response.status_code == 200
```
---
## 3. Parametrize
Use `@pytest.mark.parametrize` to test multiple inputs without duplicating test functions.
### Basic parametrize
```python
@pytest.mark.parametrize("input_val, expected", [
("alice", True),
("", False),
("a" * 256, False),
("bob@", False),
])
def test_is_valid_username(input_val, expected):
assert is_valid_username(input_val) == expected
```
### Testing edge cases systematically
Think about these categories for each function:
- **Valid inputs** — normal cases that should succeed
- **Boundary values** — empty strings, zero, max length, off-by-one
- **Invalid inputs** — wrong types, malformed data, None
- **Error cases** — inputs that should raise specific exceptions
```python
@pytest.mark.parametrize("amount, expected", [
(100, "$1.00"), # normal
(0, "$0.00"), # zero
(1, "$0.01"), # minimum
(99999, "$999.99"), # large value
])
def test_format_currency(amount, expected):
assert format_currency(amount) == expected
@pytest.mark.parametrize("amount", [-1, -100])
def test_format_currency_rejects_negative(amount):
with pytest.raises(ValueError):
format_currency(amount)
```
---
## 4. Mocking
### When to mock
- **Mock**: external services (APIs, email, payment), system clock, file system operations, slow or nondeterministic operations.
- **Don't mock**: your own code under test, data structures, pure functions. Prefer real objects when practical.
### monkeypatch (preferred for simple cases)
```python
def test_get_api_data(monkeypatch):
def mock_get(url):
return MockResponse(json_data={"result": "ok"})
monkeypatch.setattr("myapp.services.requests.get", mock_get)
data = get_api_data()
assert data["result"] == "ok"
```
### monkeypatch for environment variables
```python
def test_config_reads_env(monkeypatch):
monkeypatch.setenv("SECRET_KEY", "test-key")
config = load_config()
assert config.secret_key == "test-key"
```
### unittest.mock for complex cases
```python
from unittest.mock import patch, MagicMock
@patch("myapp.services.send_email")
def test_registration_sends_welcome_email(mock_send):
register_user("alice@example.com")
mock_send.assert_called_once_with(
to="alice@example.com",
subject="Welcome",
)
```
---
## 5. Test Quality Checklist
After completing a set of tests, review against this checklist:
- [ ] **Every public function/route has at least one test.**
- [ ] **Tests are isolated** — no test depends on another test's state or execution order.
- [ ] **No hardcoded paths or ports** — use fixtures and configuration.
- [ ] **Assertions are specific** — test exact values, not just truthiness (`assert x == 5`, not `assert x`).
- [ ] **Error paths are tested** — not just the happy path.
- [ ] **Test names describe behavior** — someone reading only test names understands what the code does.
- [ ] **Fixtures are minimal** — each fixture sets up only what is needed, no "god fixtures" with everything.
- [ ] **No logic in tests** — tests should not contain `if`, `for`, or `try/except`. Each test is a straight line.
- [ ] **Mocks are focused** — only mock what is necessary. Over-mocking makes tests brittle.
- [ ] **Tests run fast** — the full suite completes in seconds. Slow tests indicate missing mocks or unnecessary I/O.
### Running with coverage
```bash
uv add --dev pytest-cov
pytest --cov=src --cov-report=term-missing -v
```
Report untested lines and suggest tests for them.
-177
View File
@@ -1,177 +0,0 @@
# Pytest TDD Workflow
Guide development using test-driven development (TDD) with pytest. Always write the test first, watch it fail, then write the minimal code to make it pass.
**Keep things simple.** Use plain `assert` statements, simple test functions, and avoid advanced patterns unless the user asks for them. When more advanced techniques (fixtures, parametrize, mocking) would help, briefly explain what they are and suggest the PYTEST-ADVANCED skill.
## Instructions
- **Never write implementation code before its test exists and fails.**
- Follow the red-green-refactor cycle below for each unit of functionality.
- Run tests after every change.
- If the project lacks pytest configuration, set it up first (Section 2).
- Explain each step as you go — the user is learning TDD.
---
## 1. The Red-Green-Refactor Cycle
Repeat this cycle for every piece of functionality:
### Red — Write a failing test
1. Write a test that describes the desired behavior.
2. Run the test. **Confirm it fails.**
3. Check that it fails for the *right reason* (e.g. `AssertionError`, not `SyntaxError`).
### Green — Make it pass
4. Write the **minimum** code needed to make the test pass. No more.
5. Run the test. **Confirm it passes.**
### Refactor — Clean up
6. Improve the code (remove duplication, clarify names) while keeping all tests green.
7. Run tests after each change.
**Label each phase** (Red/Green/Refactor) when presenting work so the workflow is visible.
---
## 2. Project Setup
### Directory layout
```
project/
├── src/
│ └── myapp/
│ └── __init__.py
├── tests/
│ └── test_myapp.py
└── pyproject.toml
```
### pyproject.toml
If pytest config does not exist, add it:
```toml
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tb=short"
```
### Install pytest
```bash
uv add --dev pytest
```
---
## 3. Writing the Failing Test (Red)
### Naming
- Test files: `test_<module>.py`
- Test functions: `test_<behavior>` — describe *what* is being tested
```python
# Good — describes behavior
def test_new_user_has_default_role():
...
def test_login_rejects_invalid_password():
...
# Bad — describes implementation
def test_user_init():
...
```
### One test at a time
Write a single test, run it, see it fail, then implement. Do not write a batch of tests upfront.
### Assert clearly
Use plain `assert` — pytest provides detailed failure messages automatically.
```python
def test_new_user_has_default_role():
user = User(name="alice")
assert user.role == "viewer"
```
### Run and confirm failure
```bash
pytest tests/test_myapp.py::test_new_user_has_default_role -v
```
Read the error. Make sure it's the failure you expect before moving on.
---
## 4. Making the Test Pass (Green)
Write the **minimal** implementation to make the test pass.
- Don't add features the test doesn't require.
- Don't handle edge cases that aren't tested yet.
- It's fine to hard-code a return value if only one test exists — the next test will force a real implementation.
Run the full test suite:
```bash
pytest -v
```
All tests must pass before moving on.
---
## 5. Refactor
With all tests green, clean up:
- Remove duplication.
- Rename for clarity.
- Simplify logic.
**Run tests after every change.** If something breaks, undo and try a smaller step.
Don't add new behavior during refactoring. If you spot missing behavior, go back to Red.
---
## 6. Testing Exceptions
When a function should raise an error, test for it:
```python
import pytest
def test_divide_by_zero_raises():
with pytest.raises(ZeroDivisionError):
divide(1, 0)
```
---
## 7. Test Quality Checklist
After completing a set of tests, review:
- [ ] **Every public function has at least one test.**
- [ ] **Tests are isolated** — no test depends on another test running first.
- [ ] **Assertions are specific** — test exact values (`assert x == 5`, not `assert x`).
- [ ] **Error paths are tested** — not just the happy path.
- [ ] **Test names describe behavior** — reading only test names tells you what the code does.
- [ ] **No logic in tests** — no `if`, `for`, or `try/except` in test functions.
- [ ] **Tests run fast.**
### Running with coverage
```bash
uv add --dev pytest-cov
pytest --cov=src --cov-report=term-missing -v
```
-412
View File
@@ -1,412 +0,0 @@
# Vue.js Basics
Guide Vue.js development using Vue 3 loaded via CDN. **No build process.** No Vite, no npm, no .vue single-file components. Import Vue and any other libraries via `<script>` tags.
**Keep things simple.** The user is learning Vue. Explain what each directive and option does. Use the Options API (not Composition API) unless asked otherwise. Use prettier for code formatting.
## Instructions
- **Always load Vue via CDN script tag** — never use npm, Vite, or a bundler.
- Components are plain JavaScript objects with inline templates, not `.vue` files.
- Explain directives and concepts as you introduce them.
- Format all HTML, CSS, and JavaScript with prettier conventions.
- If a more advanced pattern (Composition API, Vue Router, Pinia) would help, briefly explain what it is and why, but default to the simpler approach.
---
## 1. Project Setup
### Directory layout
```
project/
├── index.html
├── js/
│ └── app.js # Vue app and components
└── css/
└── style.css
```
### HTML boilerplate
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My App</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="app">
<!-- Vue templates go here -->
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="js/app.js"></script>
</body>
</html>
```
Key points:
- Vue script tag goes before `app.js` so Vue is available when your code runs.
- The `<div id="app">` is where Vue mounts — everything inside it becomes a Vue template.
- Use `vue.global.js` (not `vue.esm-browser.js`) for script-tag usage.
---
## 2. Creating an App
### Minimal app
```js
// js/app.js
const app = Vue.createApp({
data() {
return {
message: "Hello, Vue!",
};
},
});
app.mount("#app");
```
```html
<!-- in index.html, inside <div id="app"> -->
<p>{{ message }}</p>
```
### Options explained
| Option | Purpose |
|--------|---------|
| `data()` | Returns an object of reactive state. Must be a function. |
| `methods` | Object of functions the template can call. |
| `computed` | Object of derived values that update automatically. |
| `watch` | Object of functions that run when a data property changes. |
| `mounted()` | Lifecycle hook — runs after the app is inserted into the page. |
---
## 3. Template Basics
### Text interpolation
```html
<p>{{ message }}</p>
<p>{{ count + 1 }}</p>
<p>{{ items.length > 0 ? "Has items" : "Empty" }}</p>
```
Double curly braces `{{ }}` output the value of a JavaScript expression. The expression is reactive — the page updates automatically when the data changes.
### Attribute binding — `v-bind` (shorthand `:`)
```html
<!-- full syntax -->
<a v-bind:href="url">Link</a>
<!-- shorthand (preferred) -->
<a :href="url">Link</a>
<img :src="imageUrl" :alt="imageDescription" />
<button :disabled="isSubmitting">Submit</button>
```
Use `:` to bind any HTML attribute to a data property.
### Conditional rendering — `v-if` / `v-else-if` / `v-else`
```html
<p v-if="items.length === 0">No items yet.</p>
<p v-else-if="items.length === 1">One item.</p>
<p v-else>{{ items.length }} items.</p>
```
`v-if` removes or adds elements from the DOM. Use `v-show` instead if you need to toggle visibility frequently (it uses CSS `display: none`).
### List rendering — `v-for`
```html
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
```
**Always provide a `:key`** — Vue uses it to track which items changed. Use a unique identifier, not the array index.
### Two-way binding — `v-model`
```html
<input v-model="searchQuery" placeholder="Search..." />
<p>You typed: {{ searchQuery }}</p>
```
`v-model` syncs an input's value with a data property. Works on `<input>`, `<textarea>`, `<select>`, and checkboxes.
---
## 4. Event Handling
### Basic events — `v-on` (shorthand `@`)
```html
<!-- full syntax -->
<button v-on:click="increment">+1</button>
<!-- shorthand (preferred) -->
<button @click="increment">+1</button>
```
```js
const app = Vue.createApp({
data() {
return { count: 0 };
},
methods: {
increment() {
this.count++;
},
},
});
```
### Passing arguments
```html
<button @click="addItem('apple')">Add Apple</button>
```
### Event modifiers
```html
<!-- prevent default form submission -->
<form @submit.prevent="handleSubmit">
<input v-model="name" />
<button type="submit">Save</button>
</form>
<!-- only trigger once -->
<button @click.once="initialize">Start</button>
```
Common modifiers: `.prevent`, `.stop`, `.once`, `.enter` (for keyboard events).
---
## 5. Computed Properties and Watchers
### Computed properties
Use computed for values derived from data. They cache their result and only recalculate when dependencies change.
```js
const app = Vue.createApp({
data() {
return {
items: [
{ name: "Milk", done: false },
{ name: "Bread", done: true },
],
};
},
computed: {
remainingCount() {
return this.items.filter((item) => !item.done).length;
},
},
});
```
```html
<p>{{ remainingCount }} items left</p>
```
**Computed vs methods:** Use computed when you are deriving a value from existing data. Use a method when you are performing an action (handling a click, submitting a form).
### Watchers
Use watchers when you need to perform a side effect in response to data changing (e.g. making an API call when a search query changes).
```js
const app = Vue.createApp({
data() {
return { searchQuery: "" };
},
watch: {
searchQuery(newValue, oldValue) {
console.log(`Search changed from "${oldValue}" to "${newValue}"`);
// e.g. fetch search results here
},
},
});
```
Watchers are for side effects. If you just need a derived value, use computed instead.
---
## 6. Components
Without a build process, components are plain JavaScript objects registered on the app.
### Defining a component
```js
// js/app.js
const TodoItem = {
props: ["item"],
template: `
<li>
<input type="checkbox" :checked="item.done" @change="$emit('toggle', item.id)" />
{{ item.name }}
</li>
`,
};
const app = Vue.createApp({
components: {
"todo-item": TodoItem,
},
data() {
return {
items: [
{ id: 1, name: "Milk", done: false },
{ id: 2, name: "Bread", done: true },
],
};
},
methods: {
toggleItem(id) {
const item = this.items.find((i) => i.id === id);
item.done = !item.done;
},
},
});
app.mount("#app");
```
```html
<div id="app">
<ul>
<todo-item
v-for="item in items"
:key="item.id"
:item="item"
@toggle="toggleItem"
></todo-item>
</ul>
</div>
```
### Key concepts
- **Props** flow data *down* from parent to child. Declare them in the `props` array (or object for validation).
- **Events** flow *up* from child to parent. Use `$emit('event-name', payload)` in the child, `@event-name="handler"` in the parent.
- **Templates** are inline strings in the component object (backtick template literals work well for multi-line).
### Props with validation
```js
const UserCard = {
props: {
name: {
type: String,
required: true,
},
role: {
type: String,
default: "viewer",
},
},
template: `
<div class="user-card">
<h3>{{ name }}</h3>
<span>{{ role }}</span>
</div>
`,
};
```
### Slots
Slots let a parent pass content into a child component's template.
```js
const Card = {
template: `
<div class="card">
<slot></slot>
</div>
`,
};
```
```html
<card>
<h2>Title</h2>
<p>Any content can go here.</p>
</card>
```
---
## 7. Fetching Data
Use `fetch()` in the `mounted()` lifecycle hook to load data when the page loads.
```js
const app = Vue.createApp({
data() {
return {
users: [],
loading: true,
error: null,
};
},
async mounted() {
try {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
this.users = await response.json();
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
},
});
```
```html
<div id="app">
<p v-if="loading">Loading...</p>
<p v-else-if="error">Error: {{ error }}</p>
<ul v-else>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
```
Always handle three states: **loading**, **error**, and **success**.
---
## 8. Best Practices Checklist
- [ ] **No build process** — Vue and all libraries loaded via `<script>` tags.
- [ ] **Formatted with prettier** — consistent indentation, quotes, and semicolons.
- [ ] **Semantic HTML** — use `<button>`, `<nav>`, `<main>`, `<header>`, `<form>` instead of `<div>` for everything.
- [ ] **`:key` on every `v-for`** — use a unique ID, not the array index.
- [ ] **Props down, events up** — children never modify props directly; they emit events.
- [ ] **Data is a function** — `data()` must return a new object, never a shared reference.
- [ ] **Components are small** — if a component template is longer than ~50 lines, consider splitting it.
- [ ] **Loading and error states** — every data fetch handles loading, error, and success.
- [ ] **No inline styles** — use CSS classes in `style.css`.
- [ ] **Accessible** — form inputs have `<label>` elements, images have `alt` attributes, buttons have descriptive text.