Archiwum kategorii: CSS

Intro to Vue.js: Rendering, Directives, and Events

Post pobrano z: Intro to Vue.js: Rendering, Directives, and Events

If I was going to sum up my experiences with Vue in a sentence, I’d probably say something like „it’s just so reasonable” or „It gives me the tools I want when I want them, and never gets in my way”. Again and again, when learning Vue, I smiled to myself. It just made sense, elegantly.

This is my own introductory take on Vue. It’s the article I wish I had when I was first learning Vue. If you’d like a more non-partisan approach, please visit Vue’s very well thought out and easy to follow Guide.

Article Series:

  1. Rendering, Directives, and Events (You are here!)
  2. Components, Props, and Slots (Coming soon!)
  3. Vue-cli (Coming soon!)
  4. Vuex (Coming soon!)
  5. Animations (Coming soon!)

One of my favorite things about Vue is that it takes all of the successful things from other frameworks, and incorporates them without getting disorganized. Some examples that stand out for me:

  • A virtual DOM with reactive components that offer the View layer only, props and a Redux-like store similar to React.
  • Conditional rendering, and services, similar to Angular.
  • Inspired by Polymer in part in terms of simplicity and performance, Vue offers a similar development style as HTML, styles, and JavaScript are composed in tandem.

Some benefits I’ve enjoyed over Vue’s competitors: cleaner, more semantic API offerings, slightly better performance than React, no use of polyfills like Polymer, and an isolated, less opinionated view than Angular, which is an MVC.

I could go on, but it’s probably better if you read their comprehensive and community-driven comparison with other frameworks. It’s worth a read, but you can skip back to it later if you’d like to dive into the code.

Let’s Get Started!

We can’t kick this off without the obligatory „Hello, world!” example. Let’s do that so you can get up and running:

<div id="app">
 {{ text }} Nice to meet Vue.
</div>
new Vue({
 el: '#app',
 data: {
   text: 'Hello World!'
 }
});

See the Pen Vue Hello World by Sarah Drasner (@sdras) on CodePen.

If you’re familiar with React, this will have some similarities. We’ve escaped into JavaScript in the middle of the content with the mustache template and used a variable, but one difference is we are working with straight up HTML instead of JSX. JSX is pretty easy to work with, but I do think it’s nice that I don’t have to spend time changing class to className, etc. You’ll also notice that this is pretty lightweight to get up and running.

Now let’s try Vue out with something I really love: loops and conditional rendering.

Conditional Rendering

Let’s say I have a set of items, like navigation, that I know I’m going to reuse. It might make sense to put it in an array to update it in a few places dynamically and consistently. In vanilla JS (with Babel) we might do something like this: create the array, then create an empty string where we add each item wrapped in an <li>, and then wrap all of that in a <ul> and add it to the DOM with innerHTML:

<div id="container"></div>
const items = [
  'thingie',
  'another thingie',
  'lots of stuff',
  'yadda yadda'
];

function listOfStuff() {
  let full_list = '';
  for (let i = 0; i < items.length; i++) {
      full_list = full_list + `<li> ${items[i]} </li>`
  }
  const contain = document.querySelector('#container');
  contain.innerHTML = `<ul> ${full_list} </ul>`;     
}

listOfStuff();

See the Pen e699f60b79b90a35401cc2bcbc588159 by Sarah Drasner (@sdras) on CodePen.

This works fine, but it’s a bit messy for something so standard. Now let’s implement that same thing with Vue’s loop with v-for:

<div id="app">
  <ul>
    <li v-for="item in items">
      {{ item }}
    </li>
  </ul>
</div>
const app4 = new Vue({
  el: '#app',
  data: {
    items: [
      'thingie',
      'another thingie',
      'lots of stuff',
      'yadda yadda'
    ]
  }
});

See the Pen Conditional Rendering in Vue by Sarah Drasner (@sdras) on CodePen.

Pretty clean and declarative. If you’re familiar with Angular, this will likely be familiar to you. I find this to be such a clean and legible way to conditionally render. If you jumped into the code and had to update it, you could do so very easily.

Another really nice offering is dynamic binding with v-model. Check this out:

<div id="app">
  <h3>Type here:</h3>
  <textarea v-model="message" class="message" rows="5" maxlength="72"></textarea><br>
  <p class="booktext">{{ message }} </p>
</div>
new Vue({
  el: '#app',
  data() {
    return {
      message: 'This is a good place to type things.'  
    }
  }
});

See the Pen Vue Book v-model basic by Sarah Drasner (@sdras) on CodePen.

You’ll probably notice two things about this demo. First, that it really took nothing at all to type directly into the book and dynamically update the text. Vue enables us to very easily set up two-way binding between the <textarea> and the <p> with v-model.

The other thing you might notice is that we’re now putting data in a function. In this example, it would work without doing so. We could have just put it in an object like our earlier examples. But this would only work for the Vue instance and be exactly the same across the application (thus, not so great for individual components). It’s OK for one Vue instance, but this will share data across all of the child components as well. It’s good practice to start putting data in a function because we’ll need to when we start using components and want them to each hold state of their own.

These aren’t the only easy input bindings available to you at all, and even v-if has an alternate, v-show, which won’t mount/unmount the component, but rather, leave it in the DOM and toggle visibility.

There are so many more directives available to you, here’s a sampling of some of the ones I use very often. A lot of these offer shortcuts as well, so I’ll show both. From here on, we’ll mostly use the shortcuts, so it’s good to at least familiarize yourself with them a little bit in this table.

Name Shortcut Purpose Example
v-if, v-else-if, v-else none Conditional Rendering <g v-if="flourish === 'A'"></g>
<g v-else-if="flourish === 'B'"></g>
<g v-else></g>
v-bind : Bind attributes dynamically, or pass props <div :style="{ background: color }"></div>
v-on @ Attaches an event listener to the element <button @click="fnName"></button>
v-model none Creates two-way binding <textarea rows="5" v-model="message" maxlength="72"></textarea>
v-pre none Skip compiling for raw content, can boost performance <div v-pre>{{ raw content with no methods}}</div>
v-once none Don’t rerender <div class=”v-once”>Keep me from rerendering</div>
v-show none Will show or hide a component/element based on state, but will leave it in the DOM without unmounting (unlike v-if) <child v-show=”showComponent”></child> (toggles visibility when showComponent is true)

There are also really nice event modifiers and other API offerings to speed up development like:

  • @mousemove.stop is comparable to e.stopPropogation()
  • @mousemove.prevent this is like e.preventDelegation()
  • @submit.prevent this will no longer reload the page on submission
  • @click.once not to be confused with v-once, this click event will be triggered once.
  • v-model.lazy won’t populate the content automatically, it will wait to bind until an event happens.

You can even configure your own keycodes.

We’ll use these in examples a bit more coming up!

Event Handling

Binding that data is all well and good but only gets us so far without event handling, so let’s cover that next! This is one of my favorite parts. We’ll use the binding and listeners above to listen to DOM events.

There are a few different ways to create usable methods within our application. Just like in vanilla JS, you can pick your function names, but methods are intuitively called, well, methods!

new Vue({
  el: '#app',
  data() {
   return {
    counter: 0
   }
  },
  methods: {
   increment() {
     this.counter++;
   }
  }
});
<div id="app">
  <p><button @click="increment">+</button> {{ counter }}</p>
</div>

We’re creating a method called increment, and you can see that this automatically binds to this and will refer to the data in this instance and component. I love this kind of automatic binding, it’s so nice to not have to console.log to see what this is referring to. We’re using shorthand @click to bind to the click event here.

Methods aren’t the only way to create a custom function. You can also use watch. The main difference is that methods are good for small, synchronous calculations, while watch is helpful with more tasking or asynchronous or expensive operations in response to changing data. I tend to use watch most often with animations.

Let’s go a little further and see how we’d pass in the event itself and do some dynamic style bindings. If you recall in the table above, instead of writing v-bind, you can use the shortcut :, so we can bind pretty easily to style (as well as other attributes) by using :style and passing in state, or :class. There are truly a lot of uses for this kind of binding.

In the example below, we’re using hsl(), in which hue calculated as a circle of degrees of color that wraps all the way around. This is good for our use as it will never fail, so as we track our mouse in pixels across the screen, the background style will update accordingly. We’re using ES6 template literals here.

new Vue({
  el: '#app',
  data() {
    return {
      counter: 0,
      x: 0
    }
  },
  methods: {
    increment() {
      this.counter++;
   },
   decrement() {
     this.counter--;
   },
   xCoordinate(e) {
     this.x = e.clientX;
   }
  }
});
<div id="app" :style="{ backgroundColor: `hsl(${x}, 80%, 50%)` }" @mousemove="xCoordinate">
  <p><button @click="increment">+</button> {{ counter }} <button @click="decrement">-</button></p>
  <p>Pixels across: {{ x }}</p>
</div>

See the Pen Showing simple event handling by Sarah Drasner (@sdras) on CodePen.

You can see that we didn’t even need to pass in the event to the @click handler, Vue will automatically pass it for you to be available as a parameter for the method. (shown as e here).

Also, native methods can also be used, such as event.clientX, and it’s simple to pair them with this instances. In the style binding on the element there’s camel casing for hyphenated CSS properties. In this example, you can see how simple and declarative Vue is to work with.

We don’t even actually need to create a method at all, we could also increase the counter directly inline in the component if the event is simple enough:

<div id="app">
  <div class="item">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/28963/backpack.jpg" width="235" height="300"/>
    <div class="quantity">
      <button class="inc" @click="counter > 0 ? counter -= 1 : 0">-</button>
      <span class="quant-text">Quantity: {{ counter }}</span>
      <button class="inc" @click="counter += 1">+</button>
    </div>
    <button class="submit" @click="">Submit</button>
  </div><!--item-->
</div>
new Vue({
  el: '#app',
  data() {
    return {
      counter: 0
    }
  }
});

See the Pen Backpack Shop Counter by Sarah Drasner (@sdras) on CodePen.

You can see that we’re updating the state directly in the @click handler without a method at all- you can also see that we can add a little bit of logic in there as well (as you wouldn’t have lower than zero items on a shopping site). Once this logic gets too complex, though, you sacrifice legibility, so it’s good to move it into a method. It’s nice to have the option for either, though.

Article Series:

  1. Rendering, Directives, and Events (You are here!)
  2. Components, Props, and Slots (Coming soon!)
  3. Vue-cli (Coming soon!)
  4. Vuex (Coming soon!)
  5. Animations (Coming soon!)

Intro to Vue.js: Rendering, Directives, and Events is a post from CSS-Tricks

A practical guide to Progressive Web Apps for organisations who don’t know anything about Progressive Web Apps

Post pobrano z: A practical guide to Progressive Web Apps for organisations who don’t know anything about Progressive Web Apps

Sally Jenkinson:

Progressive Web Apps (sometimes referred to as PWAs, because everything in tech needs an acronym) is the encapsulating term for websites following a certain approach, that meet particular technical criteria. The „app” involvement in the name isn’t an accident – these creations share much of the functionality that you’ll find in native experiences – but really, they’re just websites.

It’s like if you build a website that is so damn good, you get to have a home screen icon on mobile devices. And good is defined by performance and progressive enhancement.

When you hear people say „I want the web to win” they typically mean „I don’t want to lose the web to proprietary app development”. PWAs seem like an early step toward making web apps not second-class citizens on mobile devices. Maybe there is a future where native app development is web development.

Direct Link to Article — Permalink


A practical guide to Progressive Web Apps for organisations who don’t know anything about Progressive Web Apps is a post from CSS-Tricks

Real CSS Tweets (Vol. I)

Post pobrano z: Real CSS Tweets (Vol. I)

We be tweetin’ all the time about web design and development stuff. In fact, @Real_CSS_Tricks, the official Twitter account for this site, is largely just an outgoing airhorn for the stuff we publish here and interesting things elsewhere. The human beings that operate this site have their own accounts.

It’s pretty interesting to see which tweets take off! Here’s a list of the most popular tweets in the last year or so.

Wanna see a decent little slider in a handful of lines of code? pic.twitter.com/zOsN4mhRFw

— CSS-Tricks (@Real_CSS_Tricks) October 23, 2016

That one turned into a blog post and demo.


Loads of icons you can make with a single element (and pseudos)https://t.co/s3VyHj2P11 pic.twitter.com/mlIkyjc86w

— CSS-Tricks (@Real_CSS_Tricks) October 16, 2016

I’d say SVG is normally the best fit for this kind of thing, but this is a damn impressive experiment. I like the websites interface in how you can hover over the parts of CSS and it shows you what part of the icon it is.


Some more helpful mini tools:

CSS Peeper: https://t.co/RRbKhut7Ea

Chrome extension that displays styling information about the current site. pic.twitter.com/bs3NtmgI3I

— CSS-Tricks (@Real_CSS_Tricks) December 23, 2016

Always helpful to have a quickie site to snag nice colors.https://t.co/h2Ei8syLEU pic.twitter.com/X0GGXyn5dE

— CSS-Tricks (@Real_CSS_Tricks) April 4, 2016

Reminder that Clippy is an *awesomely helpful* little app for clip-pathhttps://t.co/SZILcdftSZ pic.twitter.com/qcKvcaTO8a

— CSS-Tricks (@Real_CSS_Tricks) April 6, 2016


Demos!

ooOOo fancy. "Aquarelle is a watercolor js effect."https://t.co/0ycH8fcyRV pic.twitter.com/NKqj0LKZf0

— CSS-Tricks (@Real_CSS_Tricks) January 16, 2017

What a cool way to show nav with what is current visible: https://t.co/u7yHR2QtlP pic.twitter.com/m53rzHD8El

— CSS-Tricks (@Real_CSS_Tricks) January 13, 2017

The Twitter heart explosion animation by @anatudor with:

1 Element
0 Images
0 JavaScripthttps://t.co/9rcDYZwjrY pic.twitter.com/tA7zaMg3xl

— CSS-Tricks (@Real_CSS_Tricks) June 29, 2016


Little bits of code:

Always so satisfying centering stuff with flexbox. pic.twitter.com/uH8u9EQhaw

— CSS-Tricks (@Real_CSS_Tricks) January 11, 2016

Native (!) smooth scrolling:

window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});

Polyfill: https://t.co/I6fHdLzDTT

— CSS-Tricks (@Real_CSS_Tricks) November 2, 2016

This was confusing me, but I think we have it sorted now.https://t.co/uRuiJTA68yhttps://t.co/cvYQA1riU4 pic.twitter.com/lQhba7QEpe

— CSS-Tricks (@Real_CSS_Tricks) January 22, 2016


Stuff right here on CSS-Tricks:

Input Masking :: https://t.co/ee1bRnPPnl pic.twitter.com/xVZUIc8XTr

— CSS-Tricks (@Real_CSS_Tricks) November 30, 2016

Sticky Footer
❶ ❷ ❸ ❹ ❺
Ways!https://t.co/4shCFk12UY pic.twitter.com/VjFmQnK65H

— CSS-Tricks (@Real_CSS_Tricks) May 25, 2016

So. Much. Info. on CSS Grid Layout.https://t.co/lTmSHGztho pic.twitter.com/D0lBxQSQxG

— CSS-Tricks (@Real_CSS_Tricks) March 29, 2016

❤️


Real CSS Tweets (Vol. I) is a post from CSS-Tricks

Build Your Next Website with Squarespace

Post pobrano z: Build Your Next Website with Squarespace

I’ve been reminded a few times lately how the web is both is a great enabler, allowing people all over the world to share ideas and build businesses, and a pain in the ass.

The other day, I listened to a gentlemen explain to me his unique startup business, a marketplace connecting two groups of people. It will be a real challenge, I thought, reaching all these people on both sides and getting them to understand how his business can help. He was up for the challenge and making great headway. His biggest problem, he said, was his website. ARG! The website should not be the limiting factor here. It should not be the hard part. The website should be the easy part. The hard part is reaching all those people that can make or break this idea.

A few weekends ago I watched a team come together and, highly reluctantly, spend their entire weekend handling frustrating infrastructure work on their website. Migrations gone haywire; upgrades being harder than they should have been. These people work with web tech, but web tech isn’t their business. Their time is better spent building their business, and on the weekend, resting their brains.

I’m not that worried about these folks. They have the expertise and resources to get through. I am worried about all the people out there who don’t. I’m worried about the people who are entrenched in a website setup that is far too complex for them and actively disrupting their work and business.

I wish more people used Squarespace.

With Squarespace, you’re getting a beautifully designed responsive site. You don’t have to worry about upgrades or security. You control everything – you don’t need permission or to call someone to change things on your site. You don’t need to worry about how domain names work, or hosting, or SSL. It makes the website the easy part so you can focus on whatever your hard part is. Plus I’ll worry about you less.

Use the offer code „CSS” at check-out to get 10% off your first purchase.

Direct Link to Article — Permalink


Build Your Next Website with Squarespace is a post from CSS-Tricks

The Media Object, A Bunch of Ways

Post pobrano z: The Media Object, A Bunch of Ways

The Media Object pattern is: image thingy on the left, heading and text on the right.

That’s what Nicole Sullivan called it and the name stuck. It’s a pretty simple pattern, but like all things web design, it can be done many ways.

Bootstrap’s version, which uses table layout in v3 and flexbox in v4.

Let’s take a crack at a lot of those ways. In these demos, I’m not particularly focusing on naming conventions, semantics, or browser support. Just possibilities.

With Floats

Certainly, we could float the image to the left!

See the Pen Media Block #1 by Chris Coyier (@chriscoyier) on CodePen.

But just floating means you get wrapping. Wrapping might be perfectly fine, or you might not want it.

I’d say in the typical media object pattern, there is no wrapping.

To fix that, we could make sure all the text is wrapped in an element, then make sure that element has padding-left equal to the width of the image and any white space between them.

See the Pen Media Block #2 by Chris Coyier (@chriscoyier) on CodePen.

Or, you could float both sides:

See the Pen Media Block #3 by Chris Coyier (@chriscoyier) on CodePen.

With Flexbox

Flexbox makes quick work of it!

See the Pen Media Block #4 by Chris Coyier (@chriscoyier) on CodePen.

Note that we’re allowing the <img> to become a flex item. We used align-items: flex-start; to make sure it doesn’t stretch out to the same height as the text.

With Tables

The media object could be a two-cell row of a table:

See the Pen Media Block #5 by Chris Coyier (@chriscoyier) on CodePen.

If you wanted to keep non-<table> markup, it’s still possible to make it behave like a table via display: table;:

See the Pen Media Block #6 by Chris Coyier (@chriscoyier) on CodePen.

With Grid

Grid layout allows us to define a set of columns. It’s quite easy to set up the first column to the fixed width we want, and the second column to take up the rest of the space.

See the Pen Media Block #7 by Chris Coyier (@chriscoyier) on CodePen.

Like in flexbox, we can avoid the image stretching itself out by aligning it to the top with align-self: start;.


I’m sure y’all can find about a dozen more ways to do it!


The Media Object, A Bunch of Ways is a post from CSS-Tricks

Align SVG Icons to Text and Say Goodbye to Font Icons

Post pobrano z: Align SVG Icons to Text and Say Goodbye to Font Icons

Elliot Dahl:

At Pivotal we’ve created an SVG icon system with React for use on our suite of products. This article is about my approach to styling the SVG icon system with CSS to make it easy and effective to use.

Alignment and icons (of any sort) will probably always be a bit tricky. It depends on two things that will be different on every site: the font and the icons. Elliot was able to get perfect alignment with Arial by pulling the icons down with bottom: -0.125em; because Arial sites right along the baseline and the icons themselves were designed with a 12.5% ring of white space around the edges. It’s a fairly common practice to design SVG icons with space along the edges (as annoying as it might be for alignment) because without the space, you might get awkward clipping on the edges with certain browsers/resolutions/zooming/etc (sorry I don’t have more detail handy).

Direct Link to Article — Permalink


Align SVG Icons to Text and Say Goodbye to Font Icons is a post from CSS-Tricks