Vue3——Vuex state management

Ask for three consecutive connections with one click

I hope you will like, follow and collect if you find it useful after reading this. Thank you! ! !

Preface

Regarding the two libraries for state management - vuex/pinia,
pinia is more suitable for vue3 and easier to use, but now many companies use vuex for a large number of projects, so you still need to understand it.
Pinia will definitely take over the mainstream in the future. Pinia is equivalent to the version of vuex5, and the official recommendation also recommends pinia. After learning vuex and then learning pinia, it will be faster because the concepts are the same.

Because vue3 (composition api) is suitable for pinia, it will be very awkward to use vuex in vue3, and there are many incompatibilities, so it is good to understand vuex, mainly to record the main uses, and come back to it when it is used in subsequent projects Just look at it, the main thing is to know how to use it.

So the best way is to write an additional options api script in addition to the setup syntax. This is also OK, and then write related operations in it.
Insert image description here
There are five core points in total, remember this directory

Understanding state management (front-end database)

In my opinion, isn't this the "database" of the front-end? It means creating a store.js to store data, and vuex is responsible for the management (responsive)

Insert image description here

I mentioned state management when I was learning about communication between parent and child components earlier, because it is very troublesome to transfer data in this way, and it is very inconvenient to manage when there are too many components. It is most appropriate to extract the data separately and manage it like a database. , this idea of ​​extraction is very important.

Insert image description here

Insert image description here

In general, the status is constantly changing. Because one-way data flow must be followed, all data changes must be completed in store.js, so as to facilitate the management of the status.
Insert image description here

vuex use

Insert image description here

store=warehouse=database

Basic use of Vuex

  • Install vuex
  • Create store
  • app.use(store)
  • tempate -> $store.state.counter

Create store

Insert image description here

One-way data flow, data cannot be changed in the component, and needs to be submitted to the store for changes.

import {
    
     createStore } from 'vuex'

const store = createStore({
    
    
  state: () => ({
    
      
    counter: 100,
    name: "coderwhy",
    level: 100,
    avatarURL: "http://xxxxxx",
    friends: [
      {
    
     id: 111, name: "why", age: 20 },
      {
    
     id: 112, name: "kobe", age: 30 },
      {
    
     id: 113, name: "james", age: 25 }
    ]
  }),

Use store in components

Insert image description here

Used in templates:

You can take it directly, but this is more cumbersome, so it is better to encapsulate it in computed and then use it.
Insert image description here

Used in options api:

Insert image description here

Used in setup:

You must add toRefs to be responsive. Changes in data still need to be committed to the store.
Insert image description here
Like vue-router,
use is a function used by vue libraries.
When using these libraries (store and router) in scripts, hooks are used. method, useRouter, useStore
(hooks: hook function, callback function, just some functions)

single state tree

There is only one store state library, but there can be many objects in it.
Insert image description here
Insert image description here

Vuex can only have one store, but it can have modules. Pinia is different and can have multiple stores.

Component gets status

Insert image description here

Use mapState (mapping method) to get the data (understood, if not possible, don’t use it)

Just use the mapState method in computed, so you can directly use the data in state without writing a long list.

How to write it in options api:

Write it in computed(). Here are the array syntax and object syntax:
Insert image description here
used in template:
Insert image description here

The advantage of object syntax is that it can be renamed, which reduces conflicts:
Insert image description here

Use mapState in setup syntax (please, please understand)

It cannot be used directly, because it is a function to use mapState directly. Several methods are mentioned in the video, so let’s remember the best method:

Insert image description here
This way you can use it directly

This is a method encapsulated by the teacher.
Insert image description here

geetters use

Some attributes need to be changed before they can be used, such as counting everyone's scores or multiplying them before using them. These operations are all done in getters.

Insert image description here
The second parameter can be getters
Insert image description here

Insert image description here

Handled in getters:
Insert image description here

Specific use:
Insert image description here
In fact, such a long expression here should be encapsulated in computed
. Example:

computed:{
    
    
	message(){
    
    
		return $store.getters.message
}
}

Mapping usage of geetters - mapGetters (don’t use it if it’s troublesome)

options api writing method

You can just write it directly and use it in the template, which is very convenient.
Insert image description here

How to write setup (also very inconvenient)

Remember these operations just to make it easier to use the data in the store

Method 1: Add toRefs to become responsive
Insert image description here
Method 2:
Insert image description here

Basic use of Mutation

These are all operated in the options api
Insert image description here

This is like operating in the methods of the parent component in a parent-child component, but using state instead of tihs.

Don’t forget to add state in the method ().
Insert image description here
The parameter name passed in is payload (you can name it casually. But it is usually called this). You can also pass in an object, so more modifications can be made. The last one is An object is passed in, called newInfo

Therefore, the corresponding event must also be sent out in the subcomponent: commit

Insert image description here
The last thing passed in here is an object, and more operations can be performed.
In addition, remember that this is the same as the previous parent-child communication. The event name is passed in. You can write it casually, but it is generally the same as the method name of the child component. This is easy to understand. It should also be consistent with the method name in mutation . be consistent

Insert image description here

Constant type (multiple one-shot specification, understand)

Add one more step, in order to prevent writing errors in a certain place, resulting in unusability, reference constants, as long as there are no errors in the constants, there will be no errors.

Create a js file of mutation_types, create a variable in it and export it. As long as the event name here is not written incorrectly, there will be no error.
Insert image description here
Import this variable in the component and use it.
Insert image description hereInsert image description here

Also import variables in the store's js file and use
Insert image description here

Insert image description here

Regarding the square brackets: I just use this variable name.
Insert image description here
It feels like it is done multiple times, mainly to prevent errors.

mapMutation helper function (understand)

Insert image description here
Everything works, it’s just syntactic sugar.
options api:
no need to write methods
Insert image description here

setup api:
extremely troublesome
Insert image description here

mutation important principle (important)

Don’t write asynchronous operations in it
Insert image description here

actions used (important from parameter: context)

Send a network request to the backend
because the real data is obtained from the network request (to be placed in the store). Due to the need for asynchronous operations, actions are triggered

So actions are used to make network data requests.

You should especially remember the difference between actions and mutations. In interviews, when asked about
actions, what you submit is a mutation, but a mutation directly changes the state
Insert image description here
and accepts a context. There are many things in it, just like a store.

Write actions in store

Context.commit('event name') is required to perform event operations. The event processing method in mutation is still called. You
Insert image description here
can see that the context is passed in. When processing the event, you still need to commit and call the function in the store for processing.

Special note: Add an Action to the event name in actions to distinguish it, otherwise the names will be the same and difficult to understand.

Use actions in components

action——dispatch (dispatch)

options:
Insert image description here

setup:

Insert image description here

Insert image description here

MapActions is also a good idea:
Insert image description here

Insert image description here

data plan

Two options

1. The data is maintained on the page
(it will be bad if the acquired data is mixed with the data you created)

2. The data is maintained in vuex (there are also modules in it, so that the data structure is clearer)

This way the structure feels clearer, that is, the data and the page are separated and not mixed together.

Insert image description here

Get data in actions

Network data address

step

  1. Create the fetchHomeMultidataAction(context) function in actions. Use fetch to get the data and finally use json to return it as data.
  2. It needs to be assigned to the data in the state so that it can be used on subsequent pages. It is still commit and the parameters are passed in and submitted to the mutation.
  3. Declare the data to be used in state
  4. Assign banners in mutation
    ( there is a problem here, that is, the data should not be passed in separately. It is better to pass an object object data in directly, otherwise you have to write it many times, which is too troublesome )

After watching the video, I finally found that it extracts the data into a separate component module (simply speaking, it is a separate js file, export and then import it in the main index.js). After watching the extraction, I found that it was
written It is much clearer and indeed more comfortable. If placed in a large store, it will look very tired.
Insert image description here


fetch gets the data, returns a promise (res), then converts it to json format, and then returns a promise (data).
Here are several different ways to get it. I think the first one is the most convenient.

    fetchHomeMultidataAction(context) {
    
    
      // 1.返回Promise, 给Promise设置then
      fetch("http://123.207.32.32:8000/home/multidata").then(res => {
    
    
        res.json().then(data => {
    
    
          console.log(data)
        })
      })
      
      //写法3 这一块在es6没有好好了解
      //手动返回promise 这里主要是缺少相关知识点了解
	  return new Promise(async (resolve, reject) => {
    
    
        // 3.await/async  异步函数自动返回promise
        const res = await fetch("http://123.207.32.32:8000/home/multidata")
        const data = await res.json()

      // 修改state数据,这里也是要传mutation里面处理,把数据传进去
        context.commit("changeBanners", data.data.banner.list)
        context.commit("changeRecommends", data.data.recommend.list)

 resolve("aaaaa")
      

Use the obtained data in the component

You need to import the data first, so you need to use the method of obtaining data in actions, dispatch. This can also be written in a life cycle function like onMounted.
Another point here is that it will be printed on the console after execution.
Insert image description here
On the page:

So here you can also see that the data to be obtained must be declared in the state in advance before it can be used.
Insert image description here
Insert image description here

You must learn promises well. Now the front-end has very high requirements for promises.

It's normal to forget. The important thing is to just look back when you need it.

Because it’s normal to forget something after learning it without using it, so you should take notes when you learn it before, so that you can pick it up quickly when the time comes.
Write more, memorize more, compare with yourself, the most important thing is to make progress every day, don't be anxious.


Basic usage of modules

Insert image description here

Module is easier to understand. It is mainly used to extract logic. For example, the previous logic of obtaining data from the server seemed very tired when it was placed in the store of index.js. At this time, it was extracted (home. js), called homeModule, and then import it, so it looks much clearer. Putting a logical thing together makes it easier to maintain at this time.

In index.js:
Insert image description here
store modules: Here is the rename
Insert image description here

Used in components:
Insert image description here
ps: There is no need to change the content in the setup.

module's local state

Insert image description here
It is also very easy to understand, that is, the state here is not the state in index.js, but the state in this file. If you want to use external data, you must use rootState.

Used in components: By default, there is no need to add a module name, but this means that the module is found globally, because the module is also globally available.
Insert image description here

In addition, be very careful when naming in the module. Be careful not to repeat the name in the store. Once repeated, the name in the store will be called, not the module. Because there is no need to add a module when calling, so at this time There are namespaces to solve this problem

Insert image description here
At this time, you need to add the module name when you get it:
Insert image description here

It’s over here, just master the usage of the module.

Just take a look at this
Insert image description here

Guess you like

Origin blog.csdn.net/Tommy__li/article/details/128761920