preface

When it comes to state management, Vuex, Redux, Flux, Mobx, etc. In fact, no matter what kind of scheme as long as the content is too much seems to be a headache, maybe you have your own solution or simple annotation and differentiation module, today let’s talk about the state management of the front end, if you have good suggestions or questions welcome to leave a comment below.

What is front-end state management?

For example, everyone in the library can enter the library to borrow and return books at will. If the number of people is small, this way can improve efficiency and reduce the process. Once the number of people is large, it will be easy to chaos, the direction of books is not clear, and even lost. So you need a librarian to specially record the record of borrowing books, that is, you want to entrust the librarian to lend books to you and return books.

In fact, most state management schemes have the idea of using administrators (such as Vuex) to regulate the borrowing and return of books in the library (the data that needs to be stored in the project)

Vuex

The proportion of Vuex in domestic business use should be the highest. Vuex is also a product based on Flux idea, and the state in Vuex can be modified. The reason is related to the operation mechanism of Vue. Vue implements bidirectional binding between view and data based on getter/setter in ES5. Therefore, the change of state in Vuex can be notified to the corresponding instruction in view through setter to realize view update. The only way to change the state in Vuex’s store is to commit mutation. Let’s take libraries as an example:

const state = {
  book: 0
}

const mutations = {
  borrow_book(state) {
    state.book ++
  }
}

/ / call
store.commit('borrow_book')
Copy the code

And what about action? Mixing asynchronous calls in mutation can make your program difficult to debug. How do you know which one goes first? Aciton can contain any asynchronous operation.

Actually, I’m just going to take Vuex and I’m going to give you a glimpse of what Vuex does, and you’re probably familiar with it, but what problem does Vuex solve?

  • Manage multiple component sharing states.
  • Global state management.
  • Status change tracking.
  • Let state management form a specification to make the code structure clearer.

In fact, most programmers are lazy just to share state with multiple components, and the rest is an afterthought. The most typical is the number of items added to the shopping cart. Adding one saves the final total through Vuex records and displays it in the next column.

The question is, since your goal is to share multiple states, why not just use the Bus?

Bus Bus

The Bus is actually a public Vue instance that handles emit and on events.

In fact, the Bus Bus is very lightweight, it doesn’t have a Dom structure, it just has instance methods.

Vue.prototype.$Bus = new Vue()
Copy the code

You can then send events via emit and receive events via ON.

// Send events
this.$Bus.$emit('borrow_book'.1)

// Receive in any component
this.$Bus.$on('borrow_book'.(book) = > {
    console.log(` borrowed${book}The book `)})Copy the code

Of course, there are also off (remove), once (listen once) and other operations interested in the search engine.

How’s that? Isn’t it easier to satisfy a shared state than Vuex? In fact, it is much simpler, but it also means that it is suitable for small and medium-sized projects. More than large projects, Bus will just leave you confused when you trace back to the source of the change and you don’t even know where it changed.

It works by publishing the idea of the subscriber. Although it is very elegant and simple, this is not advocated in Vue and most of the related apis (emit, ON, etc.) have been removed in 3.0. This is not the case.

class Bus {
	constructor() {
		// Collect subscription information, dispatch center
		this.list = {};
	}

	/ / subscribe
	$on(name, fn) {
		this.list[name] = this.list[name] || [];
		this.list[name].push(fn);
	}

	/ / release
	$emit(name, data) {
		if (this.list[name]) {
                    this.list[name].forEach((fn: Function) = >{ fn(data); }); }}// Unsubscribe
	$off(name) {
		if (this.list[name]) {
			delete this.list[name]; }}}export default Bus;

Copy the code

Simple, right? You just instantiate it and use it like you would with Vue Bus. What? If you want to share two or three or fewer states (one), is it unnecessary to encapsulate a Bus? Ok, you can use Web storage.

web storage

In fact, storage is just a way of storing data, with state management actually has no big relationship, just share data. But while we’re at it, by the way (Dog head)

Web storage has three types: Cookie, Local storage, and Session storage.

Either of these three is strongly advised not to put sensitive information in it, in this case encrypted or some less important data.

A quick review of the three:

category The life cycle Storage capacity Storage location
cookie By default, it is stored in memory and will expire when the browser closes. (If the expiration time is set, it will expire after the expiration time is reached.) 4KB Save it on the client side and bring it with you on every request
localStorage Theoretically permanent unless actively removed. 4.98MB (different browsers, Safari 2.49 MB) Save to the client and do not interact with the server. Save Network Traffic
sessionStorage This parameter is valid only in the current web session and will be cleared after you close the page or browser. 4.98MB (no limit in some browsers) Same as above

Cookie needless to say, when people initiate requests, they often carry cookies to request personal data and so on, which has nothing to do with what we’re going to talk about.

LoaclStorage can store permanently valid data, if you want to store state generally recommended sessionStorage, localStorage also has the following limitations:

  • Browsers have different sizes, and Internet Explorer versions later than Internet Explorer 8 support localStorage.
  • Currently, all browsers limit the value type of localStorage to string, which requires some conversion to the common JSON object type.
  • LocalStorage is not readable under the browser’s privacy mode.
  • LocalStorage is essentially a string read. If you store too much content, memory space will be consumed and pages will become jammed.
  • LocalStorage cannot be retrieved by crawlers.

The only difference between localStorage and sessionStorage is that localStorage is a permanent storage, whereas sessionStorage is a key/value pair that is cleared when the session ends.

LocalStorage itself only supports string storage, so if you store an integer, you’ll get a string.

SessionStorage is basically the same as localStorage, except that when the call is closed, the data will be emptied.

conclusion

Either way, it’s best practice to choose the right solution for your project. There is no best plan, only the right plan.

The above is only a slight talk, may not be comprehensive, welcome to leave a comment below ~