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.
npm init vue@latest # Invokes `create-vue` which presents a terminal menu # with prompts to help set up your project.
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.
Attribute/Prop binding with v-bind, or the short-hand :.
<div v-bind:class="activeClass">Hi</div><div :class="activeClass">Hi</div> <!-- You can optionally omit v-bind and just use a colon since attribute binding is so frequently used. -->
Conditional rendering with v-if, v-else-if and v-else. Whenever you use these, the elements must be consecutive siblings.
Combining v-bind and v-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 use v-model.
Two-way data binding with v-model. It’s just syntactic sugar around v-bind and v-on for creating two-way form bindings.
Just like React, you can attach a reference to an element and then access and manipulate it after it’s been mounted.
<script>export default { mounted() { this.$refs.animal.innerHTML = "🐕 dogs are better"; },};</script><template> <div ref="animal">🐈 cats are better</div></template>
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.
<!-- ChildComponent.vue --><script>export default { methods: { notifyParent() { this.$emit("someEvent", "Hello World!!!"); }, },};</script><template> <button @click="notifyParent">Click me</button></template><!-- Then in the parent component, you add an event listener for 'someEvent' --><ChildComponent @someEvent="..." />
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 the scoped prop to apply styles globally. For SCSS, you can set the prop lang="scss".
Include a .css file from somewhere in the project directory through <style scoped>@import '...'</style> or use an ES import '___.css'.
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.