preface

How is vuex used in VUe2 and VUe3? What’s the difference? How does Vuex persist in VUE3? This article will answer your questions. Take a look


What is VUex?

Liverpoolfc.tv: vuex

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

Vuex can centrally manage common data in a project. With the help of vUE debugging tools, you can record every change and who made it.

1. Modules in VUEX

Vuex consists of five modules:

  • State ——–> The data to be managed is stored here
  • Mutations ——-> The only place you can change state simultaneously
  • Actions ——-> Change state asynchronously, essentially via mutations
  • Getters ——-> Computed properties in similar components
  • Modules ——-> If vuex needs to manage a lot of data, it can be broken down into modules

2. Get started

I don’t want to tell you too much about vuex, but take a look at the previous blog: get a quick look at vuex and how to use it in VuE2

2. Use vuex in VUE3

1. Prepare

  • src/storeNew foldermodulesfolder
  • modulesNew folderuser.jsfile

The code is as follows (example) :

/ / user
export default {
  // Enable the namespace
  namespaced: true.state: {
    info: {
      uname: 'Leo'.age: 21}},mutations: {
    updateUname(state, val) {
      state.info.uname = val
    },
    updateAge(state, val) {
      state.info.age = val
    }
  },
  actions: {
    asyncUpdate(store, val) {
      setTimeout(() = > {
        store.commit('updateAge', val)
      }, 2000)}},getters: {
    format(state) {
      return state.info.uname + ',nice to meet you~'}}}Copy the code
  • modulesNew folderglobal.jsThe file is used as a public template and the namespace is not enabled

The code is as follows (example) :

/ / global
export default {
  state: {},
  mutations: {},
  actions: {},
  getters: {}}Copy the code
  • src/storeUnder folderindex.jsImport the above two files into the file
import { createStore } from 'vuex'

import global from './modules/global.js'
import user from './modules/user.js'

export default createStore({
  // Public templates can be expanded directly here. global,modules: {
    user
  }
})

Copy the code

2. Use

Used in any.vue ending file

The code is as follows (example) :

<template> <div> sync state: {{$store. State. The user. The info. The uname}} < / div > < p > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- < / p > < div > asynchronous modify state: {{$store. State. The user. The info. The age}} < / div > < p > -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- < / p > < div > getters data: {{$store.getters['user/format'] }}</div>
  <button @click="handleClick"</button> </template> <script> import {useStore} from'vuex'
export default {
  name: 'App'.setup() {
    const store = useStore()
    const handleClick = () => {
      console.log(store)
      
      store.commit('user/updateUname'.'Tom')

      store.dispatch('user/asyncUpdate'23)},return { handleClick }
  }
}
</script>

Copy the code

Conclusion:

  1. The order of execution in setup isbeforeCreateandcreatedEarlier (vue3 setup replaced the two lifecycle hook functions)
  2. There is no this in Vue3. What is needed for composing API writing
  3. To process the data in VUEX, it needs to be imported from VUEX on demanduseStore
  4. The template is similar to vue2

Vuex persistence

1. Why persistence?

If the initialization is not done, the page is refreshed, the code in VUEX is re-executed, and the data is lost.

2. How to make persistent processing?

The manual persistence code is more fragmented, and vuex provides packages for persistence.

  • Install dependencies

npm i vuex-persistedstate

  • Initialize the

In the index.js file under the SRC /store file

import createPersistedstate from 'vuex-persistedstate'

export default createStore({
  // omit others
  plugins: [
    createPersistedstate({
      key: 'saveInfo'.paths: ['user'.'cart']]}}))Copy the code

3. Effect display

Note: The default storage is localStorage

Conclusion:

  1. Implement data persistence in VUEX based on the third package
  2. The condition that triggers persistence is a change in state

conclusion

can’t stop step