Vue.js is a JavaScript framework for building sophisticated UI components in a reusable, maintainable and performant way. Just like for React, there’s a rich ecosystem of npm packages you can plug in to have things like: unit testing, static site generation, client-side routing, state management, etc.
Setup
Just run the following.
Core Things to Know
This section contains all the main things to know to be able to work on a Vue project.
Writing Components
Components are defined in a single .vue
file. Vue provides a template syntax that extends regular HTML.
You can embed any javascript expression inside the double braces, eg. {{ 42 + Math.PI }}
Props
Just like React components, every Vue component can take in props.
V- Directives
Directives start with v-
and are introduced by Vue’s template syntax. See the full list of built-in directives.
- Attribute/Prop binding with
v-bind
, or the short-hand:
. - Conditional rendering with
v-if
,v-else-if
andv-else
. Whenever you use these, the elements must be consecutive siblings. - List rendering with
v-for
. - Event listeners with
v-on
, or the short-hand@
. Combiningv-bind
andv-on
lets you have two-way data binding where changes to the UI will change the state, and changing the state will change the UI. Alternatively you can usev-model
. - Two-way data binding with
v-model
. It’s just syntactic sugar aroundv-bind
andv-on
for creating two-way form bindings.
Computed Properties
When you want to interpolate values inside the component but the expression is complex, you should extract it out into a computed property.
Lifecycle Hooks
Just like React components, Vue components undergo a similar lifecycle consisting of creation, mounting, updating and unmounting.
Refs
Just like React, you can attach a reference to an element and then access and manipulate it after it’s been mounted.
Emits
Unlike React, you can make the child trigger events on the parent directly by emitting an event from the child which hits an event handler in the parent.
Styling
Broadly, there are 2 approaches to applying CSS to Vue components.
- Add a
<style scoped>
to the .vue file where the CSS within applies only to that component. You could omit thescoped
prop to apply styles globally. For SCSS, you can set the proplang="scss"
. - Include a .css file from somewhere in the project directory through
<style scoped>@import '...'</style>
or use an ESimport '___.css'
.
Vuex
See state management.
Vuex, designed after the Flux and Redux state management frameworks, introduces a single source of truth to the app that any component can read/write to.