Skip to content

Adding docs for the class directive #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 29, 2018
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions content/guide/07-element-directives.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,96 @@ Use actions for things like:
}
}
```

#### Classes

Classes let you toggle classes on and off on your elements.

```html
<!-- { title: 'Classes' } -->
<ul class="links">
<li class:active="url === '/'"><a href="/" on:click="goto(event)">Home</a></li>
<li class:active="url.startsWith('/blog')"><a href="/blog/" on:click="goto(event)">Blog</a></li>
<li class:active="url.startsWith('/about')"><a href="/about/" on:click="goto(event)">About</a></li>
</ul>

<script>
export default {
methods: {
goto(event) {
event.preventDefault();
this.set({ url: event.target.pathname });
}
}
}
</script>

<style>
.links {
list-style: none;
}
.links li {
float: left;
padding: 10px;
}
/* classes added this way are processed with encapsulated styles, no need for :global() */
.active {
background: #eee;
}
</style>
```

```json
/* { hidden: true } */
{
"url": "/"
}
```

Classes will work alongside class attributes. If you find yourself adding multiple ternary statements inside a class attribute, classes can simplify your component. Classes also are recognized by the compiler and <a href="#scoped-styles">scoped correctly</a>.

If your class name is the same as a component variable you can use the shorthand of a class binding.

```html
<!-- { title: 'Classes shorthand' } -->
<div class:active class:is-selected>
<p>Active? {active}</p>
<p>Selected? {isSelected}</p>
</div>
<button on:click="set({ active: !active })">Toggle Active</button>
<button on:click="set({ isSelected: !isSelected })">Toggle Selected</button>

<script>
export default {
computed: {
// Because shorthand relfects the var name, you must use component.set({ "is-selected": true }) or use a computed
// property like this. It might be better to avoid shorthand for class names which don't make good variable names.
"is-selected": ({ isSelected }) => isSelected
}
}
</script>

<style>
div {
width: 300px;
border: 1px solid #ccc;
background: #eee;
margin-bottom: 10px;
}
.active {
background: #fff;
}
.is-selected {
border-color: #99bbff;
box-shadow: 0 0 6px #99bbff;
}
</style>
```

```json
/* { hidden: true } */
{
"active": true,
"isSelected": false,
}
```