Google News
logo
Vue.JS Interview Questions
You can define custom key modifier aliases via the global config.keyCodes. There are few guidelines for the properties
 
* You can't use camelCase. Instead you can use kebab-case with double quotation marks
* You can define multiple values in an array format
Vue.config.keyCodes = {
  f1: 112,
  "media-play-pause": 179,
  down: [40, 87]
}​
Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,
 
* .ctrl
* .alt
* .shift
* .meta

Lets take an example of control modifier with click event,
<!-- Ctrl + Click -->
<div @click.ctrl="doSomething">Do something</div>
In VueJS 2.x, every component must have a single root element when template has more than one element. In this case, you need to wrap the elements with a parent element.
<template>
   <div class="todo-item">
       <h2>{{ title }}</h2>
       <div v-html="content"></div>
   </div>
</template>
Otherwise there will an error throwing, saying that "Component template should contain exactly one root element...".
 
Whereas in 3.x, components now can have multiple root nodes. This way of adding multiple root nodes is called as fragments.
<template>
     <h2>{{ title }}</h2>
     <div v-html="content"></div>
</template>
If you want child wants to communicate back up to the parent, then emit an event from child using $emit object to parent,
Vue.component('todo-item', {
  props: ['todo'],
  template: `
    <div class="todo-item">
      <h3>{{ todo.title }}</h3>
      <button v-on:click="$emit('increment-count', 1)">
        Add
      </button>
      <div v-html="todo.description"></div>
    </div>
  `
})
Now you can use this todo-item in parent component to access the count value.
<ul v-for="todo in todos">
  <li>
    <todo-item
      v-bind:key="todo.id"
      v-bind:todo="todo"
      v-on:increment-count="total += 1"
    /></todo-item>
  </li>
</ul>
<span> Total todos count is {{total}}</span>
The custom events can also be used to create custom inputs that work with v-model. The <input> inside the component must follow below rules,
 
* Bind the value attribute to a value prop
* On input, emit its own custom input event with the new value.

Let's take a custom-input component as an example,
Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    />
  `
})
Now you can use v-model with this component,
<custom-input v-model="searchInput"></custom-input>
In local registration, you need to create each component in components folder(optional but it is recommended) and import them in another component file components section.
 
Let's say you want to register component A and B in component C, the configuration seems as below,
import ComponentA from './ComponentA'
import ComponentB from './ComponentB'

export default {
  components: {
    ComponentA,
    ComponentB
  },
  // ...
}
Now both ComponentA and ComponentB can be used inside ComponentC‘s template.
 
In global registration, you need to export all common or base components in a separate file. But some of the popular bundlers like webpack make this process simpler by using require.context to globally register base components in the below entry file(one-time).
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of the components folder
  './components',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})
In Vue.js, local registration is required when the global registration seems not ideal. For example, suppose you are using a build system like Webpack and globally registering all components. In that case, even if we stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download. In these cases, it is better to define your components as plain JavaScript objects as follows:
var ComponentA = {/*.......*/}   
var ComponentB = {/*.......*/}   
var ComponentC = {/*.......*/}  
After that define the components you would like to use in a components option as follows:
new Vue({  
el: '#app',  
components: {  
'component-a': ComponentA,  
'component-b': ComponentA  
}  
})  
The three modifiers supported for the v-model directive in Vue.js :
 
lazy : By default, the v-model directive syncs the input with the data after each input event. We can add the lazy modifier to instead sync after change events.
<!-- synced after "change" instead of "input" -->  
<input v-model.lazy="msg" >   

 

number : The number modifier is used to our v-model when we want user input to be automatically typecast as a number. With the type="number", the value of HTML input elements always returns a string. That's why this typecast modifier is required.
<input v-model.number="age" type="number">  ​

 

trim : We should add the trim modifier to our v-model when we want whitespace from user input to be trimmed automatically.
<input v-model.trim="msg">  
In Vue.js, if you are using vue-router, you should use router.go(path) to navigate to any particular route. You can access the router from within a component using this.$router. router.go() changed in Vue.js 2.0. You can use router.push({ name: "yourroutename"}) or just router.push("yourroutename") now to redirect.
All props follows a one-way-down binding between the child property and the parent one. i.e, When the parent property is updated then that latest prop value will be passed down to the child, but not the otherway(child to parent) around. The child component should not mutate the prop otherwise it throws a warning in the console. The possible mutation cases can be solved as below,
 
* When you try to use parent prop as initial value for child property:
 
In this case you can define a local property in child component and assign parent value as initial value
props: ['defaultUser'],
data: function () {
  return {
    username: this.defaultUser
  }
}

*
When you try to transform the parent prop :
 
You can define a computed property using the prop’s value,
props: ['environment'],
computed: {
  localEnvironment: function () {
    return this.environment.trim().toUpperCase()
  }
}