logo
eng-flag

Vue.js Cheatsheet

Table of Contents

  1. Vue Instance
  2. Template Syntax
  3. Computed Properties and Watchers
  4. Class and Style Bindings
  5. Conditional Rendering
  6. List Rendering
  7. Event Handling
  8. Form Input Bindings
  9. Components
  10. Prop
  11. Custom Events
  12. Slots
  13. Dynamic & Async Components
  14. Transitions
  15. Mixins
  16. Directives
  17. Filters
  18. Plugins
  19. State Management (Vuex)
  20. Routing (Vue Router)

Vue Instance

Creating a Vue Instance

const app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})

Lifecycle Hooks

new Vue({
  data: {
    a: 1
  },
  created() {
    console.log('Created!')
  },
  mounted() {
    console.log('Mounted!')
  },
  updated() {
    console.log('Updated!')
  },
  destroyed() {
    console.log('Destroyed!')
  }
})

Template Syntax

Text Interpolation

<span>Message: {{ msg }}</span>

Raw HTML

<p>Using v-html directive: <span v-html="rawHtml"></span></p>

Attributes

<div v-bind:id="dynamicId"></div>

JavaScript Expressions

{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}

Computed Properties and Watchers

Computed Property

computed: {
  reversedMessage() {
    return this.message.split('').reverse().join('')
  }
}

Watcher

watch: {
  question(newQuestion, oldQuestion) {
    this.answer = 'Waiting for you to stop typing...'
    this.debouncedGetAnswer()
  }
}

Class and Style Bindings

Class Binding

<div v-bind:class="{ active: isActive }"></div>

Style Binding

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

Conditional Rendering

v-if

<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>

v-show

<h1 v-show="ok">Hello!</h1>

List Rendering

v-for with Array

<ul id="example-1">
  <li v-for="item in items" :key="item.id">
    {{ item.message }}
  </li>
</ul>

v-for with Object

<ul id="v-for-object" class="demo">
  <li v-for="(value, name) in object">
    {{ name }}: {{ value }}
  </li>
</ul>

Event Handling

Click Event

<button v-on:click="counter += 1">Add 1</button>

Method Event Handlers

<button v-on:click="greet">Greet</button>
methods: {
  greet(event) {
    alert('Hello ' + this.name + '!')
    if (event) {
      alert(event.target.tagName)
    }
  }
}

Form Input Bindings

Text

<input v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>

Checkbox

<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{ checked }}</label>

Radio

<input type="radio" id="one" value="One" v-model="picked">
<label for="one">One</label>
<input type="radio" id="two" value="Two" v-model="picked">
<label for="two">Two</label>
<span>Picked: {{ picked }}</span>

Components

Global Registration

Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

Local Registration

var ComponentA = { /* ... */ }

new Vue({
  components: {
    'component-a': ComponentA
  }
})

Prop

Passing Props

<blog-post title="My journey with Vue"></blog-post>

Prop Validation

Vue.component('my-component', {
  props: {
    propA: Number,
    propB: [String, Number],
    propC: {
      type: String,
      required: true
    },
    propD: {
      type: Number,
      default: 100
    },
    propE: {
      type: Object,
      default() {
        return { message: 'hello' }
      }
    }
  }
})

Custom Events

Emitting Custom Events

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
})

Slots

Single Slot

<navigation-link url="/profile">
  Your Profile
</navigation-link>

Named Slots

<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

Dynamic & Async Components

Dynamic Components

<component v-bind:is="currentTabComponent"></component>

Async Components

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    resolve({
      template: '<div>I am async!</div>'
    })
  }, 1000)
})

Transitions

Basic Transition

<transition name="fade">
  <p v-if="show">hello</p>
</transition>
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}

Mixins

Basic Mixin

var myMixin = {
  created() {
    this.hello()
  },
  methods: {
    hello() {
      console.log('hello from mixin!')
    }
  }
}

var Component = Vue.extend({
  mixins: [myMixin]
})

Directives

Custom Directive

Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})

Filters

Defining a Filter

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

Plugins

Using a Plugin

Vue.use(MyPlugin, { someOption: true })

State Management (Vuex)

Store

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  },
  getters: {
    doubleCount: state => {
      return state.count * 2
    }
  }
})

Routing (Vue Router)

Basic Router

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo },
    { path: '/bar', component: Bar }
  ]
})

const app = new Vue({
  router
}).$mount('#app')
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
router.push('home')
router.push({ path: 'home' })
router.push({ name: 'user', params: { userId: '123' } })

2024 © All rights reserved - buraxta.com