FrontendDeveloper.in

Vue.js Interview Questions

  • Question 151

    How do you inject store into child components?

    Vuex provides a mechanism to "inject" the store into all child components from the root component with the store option. It will be enabled by vue.use(vuex).

    For example, let's inject into our app component as below,

    const app = new Vue({
    el: '#app',
    // provide the store using the "store" option.
    // this will inject the store instance to all child components.
    store,
    components: { Greeting },
    template: `
    <greeting></greeting>
    `
    })
    

    Now the store will be injected into all child components of the root and will be available on them as **this.$store **

    // let's create a hello world component
    const Greeting = {
    template: `<div>{{ greet }}</div>`,
    computed: {
    greet () {
    return this.$store.state.msg
    }
    }
    }
    
  • Question 152

    What is mapState helper?

    In Vuex application, creating a computed property every time whenever we want to access the store's state property or getter is going to be repetitive and verbose, especially if a component needs more than one state property. In this case, we can make use of the mapState helper of vuex which generates computed getter functions for us.

    Let's take an increment example to demonstrate mapState helper,

    // in full builds helpers are exposed as Vuex.mapState
    import { mapState } from 'vuex'
    
    export default {
    // ...
    computed: mapState({
    // arrow functions can make the code very succinct!
    username: state => state.username,
    
    // passing the string value 'username' is same as `state => state.username`
    usernameAlias: 'username',
    
    // to access local state with `this`, a normal function must be used
    greeting (state) {
    return this.localTitle + state.username
    }
    })
    }
    

    We can also pass a string array to mapState when the name of a mapped computed property is the same as a state sub tree name

    computed: mapState([
    // map this.username to store.state.username
    'username'
    ])
    
  • Question 153

    How do you combine local computed properties with mapState helper?

    You can use object spread operator syntax in order to combine mapState helper(which returns an object) with other local computed properties. This way it simplify merging techniques using utilities.

    computed: {
    localComputed () { /* ... */ },
    // mix this into the outer object with the object spread operator
    ...mapState({
    // ...
    })
    }
    
  • Question 154

    Do you need to replace entire local state with vuex?

    No, if a piece of state strictly belongs to a single component, it could be just fine leaving it as local state. i.e, Even though vuex used in the application, it doesn't mean that you need to keep all the local state in vuex store. Other than that the code becomes more verbose and indirect although it makes your state mutations more explicit and debuggable.

  • Question 155

    What are vuex getters??

    Vuex getters acts as computed properties for stores to compute derived state based on store state. Similar to computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.

    Let's take a todo example which as completedTodos getter to find all completed todos,

    const store = new Vuex.Store({
    state: {
    todos: [
    { id: 1, text: 'Vue course', completed: true },
    { id: 2, text: 'Vuex course', completed: false },
    { id: 2, text: 'Vue Router course', completed: true }
    ]
    },
    getters: {
    completedTodos: state => {
    return state.todos.filter(todo => todo.completed)
    }
    }
    })
    

    Note: Getters receive state as first argument.

  • Question 156

    What is a property style access?

    You can access values of store's getter object(store.getters) as properties. This is known as property style access.

    For example, you can access todo's status as a property,

    store.getters.todosStatus
    

    The getters can be passed as 2nd argument for other getters. For example, you can derive completed todo's count based on their status as below,

    getters: {
    completedTodosCount: (state, getters) => {
    return getters.todosStatus === 'completed'
    }
    }
    

    Note: The getters accessed as properties are cached as part of Vue's reactivity system.

  • Question 157

    What is a method style access?

    You can access store's state in a method style by passing arguments.

    For example, you can pass user id to find user profile information as below,

    getters: {
    getUserProfileById: (state) => (id) => {
    return state.users.find(user => user.id === id)
    }
    }
    

    After that you can access it as a method call,

    store.getters.getUserProfileById(111); {id: '111', name: 'John', age: 33}
    
  • Question 158

    What is mapGetter helper??

    The mapGetters is a helper that simply maps store getters to local computed properties.

    For example, the usage of getters for todo app would be as below,

    import { mapGetters } from 'vuex'
    
    export default {
    computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
    'completedTodos',
    'todosCount',
    // ...
    ])
    }
    }
    
  • Question 159

    What are mutations?

    Vuex mutations are similar to any events with a string type and a handler. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.

    For example, the counter example with increment mutation would be as below,

    const store = new Vuex.Store({
    state: {
    count: 0
    },
    mutations: {
    increment (state) {
    // mutate state
    state.count++
    }
    }
    })
    

    You can't directly invoke mutation instead you need to call store.commit with its type. The above mutation would be triggered as follows

    store.commit('increment')
    
  • Question 160

    How do you commit with payload?

    You can also pass payload for the mutation as an additional argument to store.commit.

    For example, the counter mutation with payload object would be as below,

    mutations: {
    increment (state, payload) {
    state.count += payload.increment
    }
    }
    

    And then you can trigger increment commit

    store.commit('increment', {
    increment: 20
    })
    

    Note: You can also pass primitives as payload.

  • Question 161

    What is object style commit?

    You can also commit a mutation is by directly using an object that has a type property.

    store.commit({
    type: 'increment',
    value: 20
    })
    

    Now the entire object will be passed as the payload to mutation handlers(i.e, without any changes to handler signature).

    mutations: {
    increment (state, payload) {
    state.count += payload.value
    }
    }
    
  • Question 162

    What are the caveats with vuex mutations?

    Since a Vuex store's state is made reactive by Vue, the same reactivity caveats of vue will apply to vuex mutations. These are the rules should be followed for vuex mutations,

    1. It is recommended to initialize store's initial state with all desired fields upfront
    2. Add new properties to state Object either by set method or object spread syntax
    Vue.set(stateObject, 'newProperty', 'John')
    

    (OR)

    state.stateObject = { ...state.stateObject, newProperty: 'John' }
    
  • Question 163

    Why mutations should be synchronous?

    You need to remember that mutation handler functions must be synchronous. This is why because any state mutation performed in the callback is essentially un-trackable. It is going to be problematic when the devtool will need to capture a "before" and "after" snapshots of the state during the mutations.

    mutations: {
    someMutation (state) {
    api.callAsyncMethod(() => {
    state.count++
    })
    }
    }
    
  • Question 164

    How do you perform mutations in components?

    You can commit mutations in components with either this.$store.commit('mutation name') or mapMutations helper to map component methods to store.commit calls.

    For example, the usage of mapMutations helper on counter example would be as below,

    import { mapMutations } from 'vuex'
    
    export default {
    methods: {
    ...mapMutations([
    'increment', // map `this.increment()` to `this.$store.commit('increment')`
    
    // `mapMutations` also supports payloads:
    'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
    add: 'increment' // map `this.add()` to `this.$store.commit('increment')`
    })
    }
    }
    
  • Question 165

    Is it mandatory to use constants for mutation types?

    No, it is not mandatory. But you might observed that State management implementations such Flux and Redux use constants for mutation types. This convention is just a preference and useful to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application.

    For example, the mutations can be declared as below,

    // mutation-types.js
    export const SOME_MUTATION = 'SOME_MUTATION'
    

    And you can configure them in store as follows,

    // store.js
    import Vuex from 'vuex'
    import { SOME_MUTATION } from './mutation-types'
    
    const store = new Vuex.Store({
    state: { ... },
    mutations: {
    // ES2015 computed property name feature to use a constant as the function name
    [SOME_MUTATION] (state) {
    // mutate state
    }
    }
    })
    
Get LinkedIn Premium at Rs 399