[Front-end interview questions] State management tool - Vuex - value transfer between any components

1. Understanding of Vuex

The core of every Vuex application is the store. A "store" is basically a container that contains most of the state in your application. Vuex differs from a pure global object in the following two ways:

  • Vuex's state storage is reactive. When a Vue component reads state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly.

  • You cannot directly change the state in the store. The only way to change the state in the store is to explicitly commit mutations. This allows us to easily track each state change, allowing us to implement some tools to help us better understand our application.

2. Usage scenarios

Using Vuex can be tedious and redundant if you don't plan to develop large single-page applications. It's true - if your app is simple enough, you're better off not using Vuex. A simple store mode is enough for what you need. However, if you need to build a medium-to-large single-page application, you will likely be thinking about how to better manage state outside of components, and Vuex will be the natural choice.

3. How to use

1、state

Definition of data in state:

state.js

//state的存放方式
const state = {
    
    
    items: []
}
export default state;

Reading data in state:

Shop.vue

1)$store.state.xx
<h2>{ { $store.state.items }}</h2>

2) Use mapState to convert to computed properties
<h2>{ { items }}</h2>
import { mapState } from "vuex";computed: mapState(["items"])

2. getters (computed properties)

Definition of getters computed properties

getters.js

//返回state中items的内容
export const items = function (state) {
    
    
    return state.items
}
//state.items的长度
export const sum = function (state) {
    
    
    return state.items.length
}

Use of getters computed properties

Shop.vue

1)$store.getters.xx
<h2>state中items:{ { $store.getters.items }}</h2>

2)mapGetters
<h2>state中items的长度:{ { sum }}</h2>
computed: { ...mapGetters(["sum"]), },

3、mutations

Definition of mutations method

小技巧:可以创建mutation-types.js来定义mutations中的方法名

/*mutation-types.js*/
export const FUN1 = 'FUN1'
export const FUN2 = 'FUN2'
/*mutations.js*/
import * as types from './mutation-types'

const mutations = {
    
    
    //新增
    [types.FUN1](state, arg) {
    
    
        state.items.push({
    
    
            id: arg.id,
            title: arg.title,
            price: arg.price,
            num: 1,
        })
    },

    //如果重复,只增加数量
    [types.FUN2](state, arg) {
    
    
        const cartItem = state.items.find(item => item.id === arg.id);
        cartItem.num++;
    }
}

export default mutations;

The use of mutations method (used in method)

  1. this.$store.commit("xxx");
  2. ...mapMutations({ fun1: "FUN1", }),

Shop.vue

<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item.id">
        <h3>{
   
   { item.title }}</h3>
        <button @click="fun1(item)">添加到购物车</button>
      </li>
    </ul>
    <h2>state中items:{
   
   { $store.getters.items }}</h2>
    <h2>state中items的长度:{
   
   { sum }}</h2>
  </div>
</template>

<script>
import {
      
       mapGetters, mapMutations } from "vuex";
export default {
      
      
  data() {
      
      
    return {
      
      
      list: [
        {
      
      
          id: 1,
          title: "物品1",
        },
      ],
    };
  },
  computed: {
      
      
    ...mapGetters(["sum", "items"]),
  },
  methods: {
      
      
    add(item) {
      
      
      this.$store.commit("FUN1", item);
    },
    ...mapMutations({
      
      
      fun1: "FUN1",
    }),
  },
};
</script>

<style>
li {
      
      
  list-style: none;
}
</style>

insert image description here
这里无法实现重复对象数量加1的效果,需要使用actions
一条重要的原则就是要记住 mutation 必须是同步函数!!!

4、actions

Action definition

/*actions.js*/
import * as types from './mutation-types'

export const addToCart = function ({
     
      commit, state }, arg) {
    
    
    const cartItem = state.items.find(item => item.id === arg.id);
    if (!cartItem) {
    
    
        commit(types.FUN1, {
    
     id: arg.id, title: arg.title })
    } else {
    
    
        commit(types.FUN2, cartItem)
    }
}

The use of actions (used in methods)

  1. this.$store.dispatch("xx", );
  2. ...mapActions({ fun1: "addToCart", }),
<!--Shop.vue-->
<template>
  <div>
    <ul>
      <li v-for="item in list" :key="item.id">
        <h3>{
   
   { item.title }}</h3>
        <button @click="fun1(item)">添加到购物车</button>
      </li>
    </ul>
    <h2>state中items:{
   
   { $store.getters.items }}</h2>
    <h2>state中items的长度:{
   
   { sum }}</h2>
  </div>
</template>

<script>
import {
      
       mapGetters, mapActions } from "vuex";
export default {
      
      
  data() {
      
      
    return {
      
      
      list: [
        {
      
      
          id: 1,
          title: "物品1",
        },
        {
      
      
          id: 2,
          title: "物品2",
        },
      ],
    };
  },
  computed: {
      
      
    ...mapGetters(["sum", "items"]),
  },
  methods: {
      
      
    add(item) {
      
      
      this.$store.commit("FUN1", item);
    },
    // ...mapMutations({
      
      
    //   fun1: "FUN1",
    // }),
    ...mapActions({
      
      
      fun1: "addToCart",
    }),
  },
};
</script>

<style>
li {
      
      
  list-style: none;
}
</style>

insert image description here

The above is the state management tool - Vuex - the value transfer between any components, pay attention to the " Front-end Interview Questions " column.
I will share the common problems in my usual projects and the knowledge of the written test and interview with you on CSDN, and make progress together. Come on.

Guess you like

Origin blog.csdn.net/weixin_46318413/article/details/122848321