What is Vuex?

Refer to the answer

Vuex is a state management plug-in developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of the application, and the only way to change the state is to submit mutation, such as this.store.com MIT (‘SET_VIDEO_PAUSE’, video_pause, SET_VIDEO_PAUSE is the method defined in the mutations property.

What problem does Vuex solve?

Refer to the answer

Solve two problems

  • When multiple components depend on the same state, it is cumbersome to pass entries to multiple nested components, and there is no way to pass state between sibling components.
  • Behaviors from different components need to change the same state. In the past, the state of multiple copies was changed and synchronized by direct reference of parent and child components or by events. These patterns are very fragile and often result in unmaintainable code.

When to use Vuex?

Refer to the answer

When a project encounters the following two scenarios

  • When multiple components depend on the same state.
  • Behaviors from different components need to change the same state.

How to quote Vuex?

Refer to the answer
  • Install dependencies firstnnpm install vuex --save
  • Create the store folder in the project directory SRC
  • Create an index.js file in the store folder and write the file
    import Vue from 'vue';
    import Vuex from 'vuex'; Vue.use(Vuex); // Not in the production environment debug astrueconst debug = process.env.NODE_ENV ! = ='production'; State :{}, getters:{}, mutations:{}, mutations:{}, mutations:{}, mutations:{}, mutations:{}, mutations:{}, mutations:{} actions:{ } })export default store;
    Copy the code
  • Then introduce Vuex into the main.js file and write like this
    import Vue from 'vue';
    import App from './App.vue';
    import store from './store';
    const vm = new Vue({
        store:store,
        render: h => h(App)
    }).$mount('#app')
    Copy the code

What are the five core attributes of Vuex?

Refer to the answer

They are state, getters, mutations, actions and Modules.

Where is the state stored in Vuex and how do you change it?

Refer to the answer

Stored in state, the only way to change state in Vuex is to explicitly commit mutation.

What should I pay attention to when using Vuex when the state is an object?

Refer to the answer

Since the object is a reference type, changing the property after replication will still affect the original data, which will change the state in state, which is not allowed, so use deep clone to copy the object first, and then modify it.

How to batch use Vuex state in components?

Refer to the answer

Use the mapState helper function to mix state into a computed object using the object expansion operator

import {mapState} from 'vuex'
exportdefault{ computed:{ ... mapState(['price'.'number'])}}Copy the code

What if you want to derive some state from state in Vuex and multiple components use it?

Refer to the answer

Using the getter property, similar to the computed property in Vue for computed, the derived state changes only when the original state changes.

Getters take two arguments, the first is state and the second is getters(which can be used to access other getters).

Const store = new Vuex.Store({state: {price: 10, number: 10, discount: 0.7,}, getters: {total: state => {return state.price * state.number
        },
        discountTotal: (state, getters) => {
            return state.discount * getters.total
        }
    },
});
Copy the code

These derived transformations can then be accessed in the component with the computed property computed using this.$store.getters. Total.

computed: {
    total() {
        return this.$store.getters.total
    },
    discountTotal() {
        return this.$store.getters.discountTotal
    }
}
Copy the code

How to use getters to get the state of a component from certain conditions?

Refer to the answer

Pass a parameter to the getter by telling it to return a function. Then judge by parameters to obtain the required state in state.

const store = new Vuex.Store({
    state: {
        todos: [
            { id: 1, text: '... '.done: true },
            { id: 2, text: '... '.done: false }
        ]
    },
    getters: {
        getTodoById: (state) => (id) =>{
            return state.todos.find(todo => todo.id === id)
        }
    },
});
Copy the code

Then in the component can be used to calculate attribute computed by enclosing $store. Getters. GetTodoById (2) to access these derived in shift.

computed: {
    getTodoById() {
        return this.$store.getters.getTodoById
    },
}
mounted(){
    console.log(this.getTodoById(2).done)//false
}
Copy the code

How to batch use the Vuex getter property in components

Refer to the answer

Use the mapGetters helper function to mix getters into a Computed object using the object expansion operator

import {mapGetters} from 'vuex'
exportdefault{ computed:{ ... mapGetters(['total'.'discountTotal'])}}Copy the code

How to batch alias Vuex getters and use them in components

Refer to the answer

Use the mapGetters helper function to mix getters into a Computed object using the object expansion operator

import {mapGetters} from 'vuex'
exportdefault{ computed:{ ... mapGetters({ myTotal:'total',
            myDiscountTotal:'discountTotal',}}}Copy the code

In THE Vuex state there is a state number which indicates the quantity of goods, how the component changes it.

Refer to the answer

First, a mutation is registered on mutations

const store = new Vuex.Store({ state: { number: 10, }, mutations: { SET_NUMBER(state,data){ state.number=data; }}});Copy the code

Use this.code.mit to commit mutation in the component to change the number

this.$store.commit('SET_NUMBER', 10)Copy the code

What to watch out for when using mutation in Vuex.

Refer to the answer

Mutation must be a synchronization function

If the same mutation is committed multiple times in a component, how to write and use it is more convenient.

Refer to the answer

MapMutations auxiliary function, which is used in the component

import { mapMutations } from 'vuex'methods:{ ... mapMutations({setNumber:'SET_NUMBER'})},Copy the code

Then call this.setnumber (10) rather than this.store.com MIT (‘SET_NUMBER’,10)

What is the difference between action and mutation in Vuex?

Refer to the answer
  • The action commits the mutation instead of directly changing the state. Mutation can change the state directly.
  • An action can contain any asynchronous operation. Mutation can only be a synchronous operation.
  • The submission method is different, the action is usedthis.$store.dispatch('ACTION_NAME',data)To submit. Mutation is to usethis.$store.commit('SET_NUMBER',10)To submit.
  • The receiving parameters are different. The first parameter of mutation is state, while the first parameter of action is context, which contains
    {state, // equivalent to 'store.state', or local state if in the module rootState, // equivalent to 'store.state', Exists only in modules commit, // equivalent to 'store.com MIT' dispatch, // equivalent to 'store.dispatch' getters, // Equivalent to 'store.getters' rootGetters // equivalent to' store.getters', exists only in modules}Copy the code

What are the similarities between action and mutation in Vuex?

Refer to the answer

The second parameter can be received from the external submission. This $store. Dispatch (” ACTION_NAME “, data) and this.$store.com MIT (‘ SET_NUMBER, 10)

When a component commits the same action multiple times, it is easier to write and use the same action.

Refer to the answer

Use the mapActions helper function to do this in a component

methods:{ ... mapActions({setNumber:'SET_NUMBER'})},Copy the code

Then call this.setnumber (10) rather than call this.$store.dispatch(‘SET_NUMBER’,10)

Actions in Vuex are usually asynchronous, so how do you know when an action ends?

Refer to the answer

The Promise is returned in the action function and then handled when the Promise is submitted

actions:{
    SET_NUMBER_A({commit},data){
        return new Promise((resolve,reject) =>{
            setTimeout(() =>{
                commit('SET_NUMBER', 10); resolve(); },2000) }) } } this.$store.dispatch('SET_NUMBER_A').then(() => {
  // ...
})
Copy the code

There are two actions in Vuex, namely actionA and actionB, which are both asynchronous operations. To submit actionA in actionB, other operations need to be processed after actionA is processed. How to achieve this?

Refer to the answer

Use async and await in ES6.

actions:{
    async actionA({commit}){
        //...
    },
    async actionB({dispatch}){
        await dispatch ('actionA')// Wait for actionA to finish //... }}Copy the code

Have you ever used the Vuex module? Why and how to use it.

Refer to the answer

Yes, because with a single state tree, all the state of the application is concentrated into one large object. When the application becomes very complex, the Store object can become quite bloated. So split the store into modules. Each module has its own state, mutations, actions, getters, and even nested submodules, which are divided in the same way from top to bottom.

Create the moduleA.js and moduleB.js files in the Module file. Write to the file

const state={
    //...
}
const getters={
    //...
}
const mutations={
    //...
}
const actions={
    //...
}
export default{
    state,
    getters,
    mutations,
    actions
}
Copy the code

Then I introduce the module with index.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import moduleA from './module/moduleA'
import moduleB from './module/moduleB'
const store = new Vuex.Store({
    modules:{
        moduleA,
        moduleB
    }
})
export default store
Copy the code

Is state, the first parameter that getters and mutations receive in a module, global or modular?

Refer to the answer

The first argument, state, is the module’s state, which is the local state.

How do you access the global state and getter in the getter and mutation and action modules?

Refer to the answer
  • In the getter, the global state can be accessed by the third argument rootState, and the global getter can be accessed by the fourth argument rootGetters.
  • Global SATAT and getters are not accessible in mutation, only local state is accessible.
  • In the first argument to the action contextcontext.rootStateTo access the global state,context.rootGettersAccess to the global getter.

How to access getters and states in the Vuex module in the component, and how to submit mutation and action?

Refer to the answer
  • Directly throughthis.$store.gettersandthis.$store.stateTo access getters and states in modules.
  • Directly throughthis.$store.commit('mutationA',data)Commit the mutation in the module.
  • Directly throughthis.$store.dispatch('actionA,data')Commit the action in the module.

Have you used the Vuex module’s namespace? Why and how to use it.

Refer to the answer

By default, actions, mutations, and getters within a module are registered in the global namespace. If action and mutation are named the same in multiple modules, The mutation and action with the same name in all modules are triggered.

There’s too much coupling, and to give your module more encapsulation and reusability, you can make it a namespace module by adding namespaced: true.

export default{
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}
Copy the code

How do I commit global mutation and action in a namespaced module?

Refer to the answer

Pass {root: true} as the third argument to Dispatch or commit.

this.$store.dispatch('actionA', null, { root: true })
this.$store.commit('mutationA', null, { root: true })
Copy the code

How do I register a global action in a module with a namespace?

Refer to the answer
actions: {
    actionA: {
        root: true, handler (context, data) { ... }}}Copy the code

How do components submit mutationA in modules with namespace in moduleA?

Refer to the answer
this.$store.commit('moduleA/mutationA',data)
Copy the code

How do you use functions mapStates, mapGetters, mapActions and mapMutations to bind modules with namespaces?

Refer to the answer

Start by using createNamespacedHelpers to create a namespace based helper function

import { createNamespacedHelpers } from 'vuex';
const { mapState, mapActions } = createNamespacedHelpers('moduleA');
exportDefault {computed: {// Look for... in 'module/moduleA' MapState ({a: state => state.a, b: state => state.b})}, methods: {// Find in 'module/moduleA'... mapActions(['actionA'.'actionB'])}}Copy the code

Has the Vuex plugin ever been used? How to use a brief introduction?

Refer to the answer

The Vuex plugin is a function that takes a store as its only argument. The plugins option is introduced in the vuex.store constructor. Write to the store/plugin.js file

export default function createPlugin(param){
    returnstore =>{ //... }}Copy the code

Then write to the store/index.js file

import createPlugin from './plugin.js'
const myPlugin = createPlugin()
const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})
Copy the code

How do I listen for mutations and actions in the Vuex plugin?

Refer to the answer
  • Use the instance method of vuex.storesubscribeListen for the commit mutation in the component
  • Use the instance method of vuex.storesubscribeActionThe listener commits an action to the store/plugin.js file
export default function createPlugin(param) {
    returnstore => { store.subscribe((mutation, State) => {console.log(mutation.type)// is that mutation console.log(mutation.payload) console.log(state)}) // store.subscribeAction((action, State) => {// console.log(action.type)// Is the action // console.log(action.payload)// commit the action parameter //}) Store.subscribeaction ({before: (action, state) => {// Console. log(' before action${action.type}}, after: (action, state) => {// after the action is committed console.log(' after action${action.type}')}})}}Copy the code

Then write to the store/index.js file

import createPlugin from './plugin.js'
const myPlugin = createPlugin()
const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})
Copy the code

How to use the value of state in Vuex on the V-model?

Refer to the answer

You need to convert using the computed computing attribute.

<input v-model="message">
// ...
computed: {
    message: {
        get () {
            return this.$store.state.message
        },
        set (value) {
            this.$store.commit('updateMessage', value)
        }
    }
}
Copy the code

What is the strict mode of Vuex, what does it do and how can it be turned on?

Refer to the answer

In strict mode, an error is thrown whenever a state change occurs that is not caused by the mutation function. This ensures that all state changes can be tracked by the debugging tool.

Open in the vuex.store constructor option, as shown below

const store = new Vuex.Store({
    strict:true,})Copy the code

Other Vue interview questions

  • Vue-router interview questions summary
  • Vue junior front end engineer interview essential
  • Vue Preliminary interview questions summary
  • Vue Intermediate interview questions summary
  • Vue advanced interview questions summary